0

I am playing around with custom Buttons by defining different states in a StateListDrawable and setting it as the background on a Button. I realized that when these different states contain png images as their background, the default AppCompatButton behavior (pull up animation, shadow etc.) gets deactivated, just leaving the plain images for the different states. But when I use the same StateListDrawable with xml shapes (example at the bottom), it keeps the default Button behavior. Why is that?

StateListDrawable:

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

Example for an xml shape:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#00CCFF"
        android:centerColor="#0000CC"
        android:endColor="#00CCFF"
        android:angle="90"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <stroke
        android:width="2dip"
        android:color="#FFFFFF" />
    <corners android:radius= "15dp" />
</shape>

Screenshots:

For testing purposes I just took the launcher icon background as the button image. You can see that if I choose the launcher image as the background, the button loses it's shadow and pull up animation. But when I use an XML shape as the background, it keeps both.

Button with Launcher Icon Background

Button with XML Shape Background

Florian Walther
  • 6,237
  • 5
  • 46
  • 104

1 Answers1

0

The behaviors are not deactivated. They're simply hidden underneath the xml drawable you created. Since the custom drawable you created has no limited size, it fills all the possible area defined by it's parent layout. In other words, it matches parent ("match_parent"). That's why you cannot see it.

On the other hand, the PNG file has precise dimensions and doesn't cover the whole area of it's parent layout so there are some space left for you to see the effects and animations like shadow. To be able see the animations also with the custom xml, I suggest you to give some padding to your button while setting your custom xml as background. Or you can use it as "wrap_content" instead of "match_parent".

Fatih
  • 507
  • 4
  • 15