点击CardView时的高度动画

10

我想给我的android.support.v7.widget.CardView添加高度动画,就像材料风格的Button一样。我已经尝试设置了一个StateListAnimator

android:stateListAnimator="@anim/selector_raise"

这指向了我在 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>

但是Android Studio给了我一个错误:

元素选择器必须被声明

正确的做法是什么?

2个回答

6

您尝试在 res/anim 文件夹中创建此 .xml 文件。

如果不存在,您应该在 res/animator 文件夹中创建,这很容易。

但是,如果您搜索该问题,它已经给出了一个可能的解决方案: enter image description here


5
我已经尝试了你的代码,也许你只是简单地将state添加到了第二个选择器元素中。因此,请更改这一行。
<item>

使用此功能

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

完整的代码将是:
<?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>

3
对我来说很有效,我将动画师移动到res/animator/my_filename.xml下。 - moatist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接