Elevation animation on click on CardView
Asked Answered
S

2

10

I want to add the elevation animation to my android.support.v7.widget.CardView, just like the material style Buttons do. I've tried to set a StateListAnimator:

android:stateListAnimator="@anim/selector_raise"

which points to my selector in res/anim:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_pressed="true">
        <objectAnimator android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ" android:valueTo="@dimen/touch_raise"
            android:valueType="floatType" />
    </item>
    <item>
        <objectAnimator android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ" android:valueTo="0dp"
            android:valueType="floatType" />
    </item>
</selector>

but Android Studio gives me the error:

Element selector must be declared

What's the right way to do that?

Sinusitis answered 12/12, 2016 at 22:43 Comment(0)
P
6

You tried to create this .xml in res/anim folder.

You should create on res/animator, if don't exist is easy to create.

But if you search for the problem it already give you a possible solution enter image description here

Pya answered 30/12, 2017 at 20:20 Comment(0)
P
5

I've tried your code, maybe you have simply add the state to second selector element.

So change this line

<item>

with this

<item android:state_enabled="true" android:state_pressed="false">

The complete code will be

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_pressed="true">
        <objectAnimator android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ" android:valueTo="@dimen/touch_raise"
            android:valueType="floatType" />
    </item>
    <item android:state_enabled="true" android:state_pressed="false">
        <objectAnimator android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ" android:valueTo="0dp"
            android:valueType="floatType" />
    </item>
</selector>
Philbo answered 3/5, 2017 at 11:20 Comment(1)
worked for me, and I moved the animator under res/animator/my_filename.xmlDebrief

© 2022 - 2024 — McMap. All rights reserved.