Ideally, to change the colour of a button whilst keeping the rest of the look and feel of the button the same, one would think that defining a style as follows and setting this to be the style of our button would do the trick:
<style name="button" parent="@android:style/Widget.Button">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@color/mycolor</item>
</style>
Unfortunately, this doesn't have the desired effect. By doing the above (i.e. setting the background property to be a colour), you'll see that your button has lost its look and feel, and is now a plain rectangle with sharp (non-rounded) corners (though it does now have the colour specified). What you need to do instead is add an xml file (let's call it mycustombutton.xml) to your res/drawable folder, which defines the shape (colour etc) of your button for the different states it might find itself in (pressed etc), as follows:
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape android:shape="rectangle" >
<solid android:color="@color/mypressedcolor" />
<corners android:radius="3dp" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="@color/mydefaultcolor" />
<corners android:radius="3dp" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</shape>
</item>
</selector>
The above specifies a curved rectangle with padding and colours for two different states (pressed and default). All that remains now is to set the background property of your button to have the value @drawable/mycustombutton.
No comments:
Post a Comment