Android 5.0 android:elevation Works for View, but not Button?
Solution 1:
The default Button style under Material has a StateListAnimator that controls the android:elevation
and android:translationZ
properties. You can remove the existing animator or set your own using the android:stateListAnimator
property.
<Button
...
android:stateListAnimator="@null" />
<Button
...
android:stateListAnimator="@anim/my_animator" />
The default animator is defined in button_state_list_anim_material.xml. Here is a sample showing the enabled and pressed states:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:state_enabled="true">
<set>
<objectAnimator android:propertyName="translationZ"
android:duration="@integer/button_pressed_animation_duration"
android:valueTo="@dimen/button_pressed_z_material"
android:valueType="floatType"/>
<objectAnimator android:propertyName="elevation"
android:duration="0"
android:valueTo="@dimen/button_elevation_material"
android:valueType="floatType"/>
</set>
</item>
<!-- base state -->
<item android:state_enabled="true">
<set>
<objectAnimator android:propertyName="translationZ"
android:duration="@integer/button_pressed_animation_duration"
android:valueTo="0"
android:startDelay="@integer/button_pressed_animation_delay"
android:valueType="floatType"/>
<objectAnimator android:propertyName="elevation"
android:duration="0"
android:valueTo="@dimen/button_elevation_material"
android:valueType="floatType" />
</set>
</item>
...
</selector>
Solution 2:
In my experience with Appcompat v7 running on Lollipop device, Button
works with default features as ripple effect, elevation and z-animation on click, but misses them if is set a personalized android:background
property (as color or selector) in xml element.
Solution 3:
This is because you are setting the background of the button manually which will replace all its effects.
As of the version 23.0.0 release of AppCompat, there is a new Widget.AppCompat.Button.Colored style which uses your theme's colorButtonNormal for the disabled color and colorAccent for the enabled color.
<Button
...
style="@style/Widget.AppCompat.Button.Colored" />
If you want different colors than specified you can create a new theme and apply it to the button via android:theme
. Then you can use this theme on all your buttons where you want same effect.
Solution 4:
I had a similar problem i thought was due to wrongly inflated layouts, but it appeared that adding clipToPadding
did the trick.
This must be set to the parent ViewGroup
containing the view you want to cast a shadow.
...
android:clipToPadding="false"
...