如何在Android程序中以编程方式加载动画器XML文件?

10
根据安卓开发者网站所述,我们可以通过以下方式从位于此路径的xml文件中编程加载AnimatorSet类:res/animator/filename.xml。因此,我创建了一个示例项目并尝试查看它是否真的起作用,但是它没有反应。如果我能理解缺少了什么和/或我做错了什么就太好了。谢谢您提前的帮助!下面是我的动画xml文件和加载xml的Java代码:

res/animator/sample.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:ordering="sequentially"
    >
  <set>
    <objectAnimator
        android:propertyName="x"
        android:duration="500"
        android:valueTo="400"
        android:valueType="intType"
        />
    <objectAnimator
        android:propertyName="y"
        android:duration="500"
        android:valueTo="300"
        android:valueType="intType"
        />
  </set>
  <objectAnimator
      android:propertyName="alpha"
      android:duration="500"
      android:valueTo="1f"
      />
</set>

这里是我的Java代码,用于加载上面的xml文件:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
  @Override public void onClick(View view) {
    // Load and start Animaton
    AnimatorSet animSet =
        (AnimatorSet) AnimatorInflater.loadAnimator(view.getContext(), R.animator.sample);
    animSet.setTarget(view);
    animSet.start();
  }
});
2个回答

31

你的设置包含另一个设置res/animator/sample.xml。 简化它。

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:ordering="sequentially"
    >

  <objectAnimator
      android:propertyName="alpha"
      android:duration="500"
      android:valueTo="1f"
      />
</set>

您可以像这样扩展AnimatorSet:

AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(getActivity(), R.animator.sample);
set.setTarget(fab); // set the view you want to animate
set.start();

到目前为止,我还没有找到一种从XML到Java膨胀objectAnimator的方法。我必须将它包装在一个Set中。


@DysaniazzZ,你能说得更清楚一些吗? - Raymond Chenon
为了避免强制转换,您可以使用Animator替代AnimatorSet。 - Mahdi Moqadasi

4

文档中给出的示例存在错误。

尝试将android:valueType="intType"更改为android:valueType="floatType"

对于@RaymondChenon,它可以正常工作,因为他没有显式更改android:valueTypeint,所以系统会使用默认值float

问题在于,在您的animator中提供了android:valueType="intType",而应该是android:valueType="floatType",用于您正在动画化的属性android:propertyName="x"

运行时系统寻找要动画化的属性的setter。像在您的情况下,它将寻找setX(),但由于您定义的参数类型为int,它会导致不匹配,因为没有这样的方法,我不知道为什么它没有导致崩溃。

查看View类的属性,有一个方法setX(float)

要进一步了解,请参阅StackOverflow问题


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