miércoles, 8 de enero de 2014

Android: Button with background and icon changing simultaneously

We will change the background in the style. I used a style since I had a lot of buttons whose background should behave the same. In each image view though we set its src to the corresponding selector.

<ImageView
            android:id="@+id/gallery_button"
            style="@style/ProgramDetailMenuItem"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:clickable="true"
            android:src="@drawable/galery_button_selector" />

res/drawable/galery_button_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
 
    <item        
android:drawable="@drawable/btn_galery_pressed"        
android:state_pressed="true"/>
    <item        
android:drawable="@drawable/btn_galery"        
android:state_enabled="true"/>

</selector>

Now we do the background color change.

res/values/styles

<resources xmlns:android="http://schemas.android.com/apk/res/android">

   ...
 
    <style name="ProgramDetailMenuItem">
       <item name="android:background">@drawable/program_detail_button_background</item>
    </style>

</resources>



res/drawable/program_detail_button_background



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

</selector>



res/values/colors



<?xml version="1.0" encoding="utf-8"?>
<resources>
    ...
    <color name="program_detail_button_pressed">#717171</color>
    <color name="program_detail_button_not_pressed">#00FFFFFF</color>
    
</resources>



The reason behind #00FFFFFF is that 00 is the alpha, and this value will set the alpha to 0 regardless of the following 6 hexa digits.

No hay comentarios:

Publicar un comentario