是否可以从另一个继承 anim xml 资源并覆盖属性?

Is it possible to inherit an anim xml resource from another and overwrite attributes?

我在 res/anim 文件夹中有这两个文件:

my_anim.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">

    <rotate
        android:duration="3000"
        android:interpolator="@android:anim/linear_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="infinite"
        android:repeatMode="restart"
        android:toDegrees="360" />

</set>

my_anim_faster.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">

    <rotate
        android:duration="1000"
        android:interpolator="@android:anim/linear_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="infinite"
        android:repeatMode="restart"
        android:toDegrees="360" />
</set>

都是一样的动画,只是速度(android:duration)变了。有没有办法让这段代码更短?例如,通过 my_anim_faster 继承自 my_anim 并覆盖 android:duration 属性或类似的东西。

谢谢。

据我所知,在 xml 中创建动画时无法继承其他动画,就像在创建布局时如何 "include" 布局一样。

您最好的选择是以编程方式创建动画(例如在 AnimationUtils class 中)并在调用它时提供持续时间作为参数。例如

MyAnim myAnim = new MyAnim(1000);

小提示:XML资源无法继承。 xml 方法使您能够轻松快速地创建可绘制对象、动画和布局等资源,但无法继承它们。 Google 添加了 fragments 允许您以某种方式扩展和重用布局功能,但这不是继承。在 drawable/animation 资源中,您可以重用其他资源,但不能扩展它们。因此,如果您想重用某些逻辑,请尝试设计您的资源,以便您可以在其他逻辑中重用它们。

现在针对您的情况:不,无法通过 xml 执行此操作。使用 xml 您只能 描述 您的资源。您可以使用 java 代码以编程方式更改持续时间。

Animation myAnimation = ...;
...
myAnimation.setDuration(1000);