Round cornered button with background color in android

人盡茶涼 提交于 2019-12-02 16:52:43

You want to use Android's Shape Drawables. http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

drawable/cool_button_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="@dimen/corner_radius" />
    <gradient
        android:angle="270"
        android:startColor="@color/almost_white"
        android:endColor="@color/somewhat_gray"
        android:type="linear" />
</shape>

Then you'd have to create a "selector" drawable from those shape drawables. This allows you to make the button appear different depending on the state. IE: Pressed, focused, etc. http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

drawable/cool_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@drawable/cool_inner_press_bottom" />
    <item android:state_focused="true" android:state_enabled="true"
        android:state_window_focused="true"
        android:drawable="@drawable/cool_inner_focus_bottom" />
    <item
         android:drawable="@drawable/cool_button_background" />
</selector>

Bonus: You might want to create a style for the button so you can have them be consistent throughout the program. You can cut this step out and just set the button's android:background="@drawable/cool_button".

values/styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCoolButton">
        <item name="android:background">@drawable/cool_button_background</item>
    </style>
</resources>

Finally, the button!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/appwidget_bg">
    <Button
        android:id="@+id/btnAction"
        android:layout_width="wrap_content"
        android:layout_weight="wrap_content"
        style="@style/CoolButton"
        />
</LinearLayout>

Import PorterDuff and use setColorFilter() as follows

import android.graphics.PorterDuff.Mode;

Button btn = (Button) findViewById(R.id.myButton); 
btn.getBackground().setColorFilter(Color.GRAY, Mode.MULTIPLY);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!