[Android] Button drawable android:state_pressed not working
by Riley MacDonald, March 13, 2018

While working with dynamically generated Buttons styled via drawable I struggled to get android:state_pressed to work. As the states of the Button changed the styles were not being applied (state_pressed="true", state_focused="true" etc).

Overview of the Button
I was constructing the Button programmatically providing a style as a constructor argument:

private Button buildButton() {
  @StyleRes int style = R.style.ButtonStyle;
 
  Button button = new Button(context, null, 0, style);
 
  // ... set button text, listener etc.
  return button;
}

The style would then apply the drawable where my states were malfunctioning:

<style name="ButtonStyle">
  <!-- Apply colors, textSize etc -->
  <item name="android:background">@drawable/my_button</item>
</style>

Finally here is the Button with a custom border defined via this Drawable (my_button.xml).

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <corners android:radius="8dip"/>
            <stroke android:width="1dip" android:color="@color/green"/>
            <solid android:color="@color/white"/>
        </shape>
    </item>
    <item android:state_pressed="false">
        <shape android:shape="rectangle">
            <corners android:radius="8dip" />
            <stroke android:width="1dip" android:color="@color/white"/>
            <gradient android:angle="-90"/>
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <corners android:radius="8dip"/>
            <stroke android:width="1dip" android:color="@color/green"/>
            <gradient android:angle="-90"/>
            <solid android:color="@color/green"/>
        </shape>
    </item>
</selector>

Solution: Ensure the button is clickable
Turns out these styles will not work if the Button flag CLICKABLE isn’t set. I assume this is set automatically by Android when a Button is constructed via xml. I was able to resolve this issue by simply setting isClickable(true) in my buildButton() method above:

<pre lang="java">
private Button buildButton() {
  @StyleRes int style = R.style.ButtonStyle;
 
  Button button = new Button(context, null, 0, style);
 
  // Fix state_pressed issue:
  button.setClickable(true);
 
  // ... set button text, listener etc.
  return button;
}
Open the comment form

Leave a comment:

Comments will be reviewed before they are posted.

User Comments:

Be the first to leave a comment on this post!