Android button select and press drawable

croigsalvador picture croigsalvador · Nov 18, 2012 · Viewed 54.2k times · Source

I'm trying to make a button with state press and select, I already did the same with tabs and it works but I don't know why here does not work. I have done it like this:

button_sel.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
       android:shape="rectangle">
    <gradient android:startColor="@color/azulado" 
              android:endColor="@color/azulBrillante"
              android:angle="270" />
     <corners android:radius="@dimen/corner_radius" />
     <stroke android:width="2px" 
             android:color="@color/blanco" />
 </shape>

button_unsel.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
       android:shape="rectangle">
    <gradient android:startColor="@color/botonesD" 
              android:endColor="@color/botones"
              android:angle="270" />
    <corners android:radius="@dimen/corner_radius" />
    <stroke android:width="2px" 
            android:color="@color/blanco" />
</shape>

And the selector, button.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_sel"  
          android:state_selected="true" 
          android:state_pressed="true"/>
<item android:drawable="@drawable/button_unsel" 
      android:state_selected="false" 
      android:state_pressed="false"/>
</selector>

And here I call the drawable as a background:

 <style name="button">
    <item name="android:background">@drawable/button</item>
    <item name="android:textSize">@dimen/text_size</item>
    <item name="android:padding">@dimen/padding_button</item>
    <item name="android:textColor">@color/blanco</item>
 </style>

Thank you!!!!

Answer

brillenheini picture brillenheini · Nov 18, 2012

The first item in your selector is only used, when the button is pressed AND selected. If you want to use button_sel when your button is pressed OR selected, you should do something like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_sel" android:state_selected="true" />
    <item android:drawable="@drawable/button_sel" android:state_pressed="true" />
    <item android:drawable="@drawable/button_unsel" />
</selector>

The items are evaluated from top to bottom, the last one is the default. Though I am not sure if state_selected makes sense for buttons.