Search code examples
androidbuttonandroid-theme

Why does a Button loses its original behaviour after changing its color?


I am writing an Android app and now I am styling it. I am using a custom theme which is a child of Theme.Holo.Light. I really like Theme.Holo.Light because its buttons have a special effect when you click and hold it. Like the lower button in the picture below:

Not click: enter image description here

click: enter image description here

The upper button has been changed color. Now when I click on that button, it doesn't have that effect. I really don't understand why. Can anyone tell me why this happens and how can I get the same effect with a colored button?

And also, the colored button seems fatter.


Solution

  • This is because the button uses a selector to display different colors/effects/drawables based on the state of the click. You can check out the link on Color State List Resource.

    To create your own you have to create a slecetor cml file and put it in your drawables folder.

    For example.

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/shape_btn_default_normal_gray" android:state_enabled="true" android:state_pressed="false"/>
        <item android:drawable="@drawable/shape_btn_default_pressed_gray" android:state_pressed="true"/>
        <item android:drawable="@drawable/shape_btn_default_disabled_gray"/>
    </selector>
    

    or with colors

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@color/dark_green" android:state_enabled="true" android:state_pressed="false"/>
        <item android:drawable="@color/light_green" android:state_pressed="true"/>
        <item android:drawable="@color/gray"/>
    </selector>
    

    To apply this you have to set the background drawable in your layout xml like this.

    <Button
        android:id="@+id/my_btn"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Some text"
        android:background="@drawable/selector_btn_default_gray"/>