开发者

Round cornered button with background color in android

I need to do round cornered button with backgr开发者_运维知识库ound color change in android.

How could i do that?

Example link/code is much appreciated.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜