AnimatedVectorDrawableCompat使用回调循环动画 [英] AnimatedVectorDrawableCompat looping animation using callback

查看:649
本文介绍了AnimatedVectorDrawableCompat使用回调循环动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AnimatedVectorDrawableCompat在Android应用中实现动画,以实现与API> = 21的兼容性。

I'm trying to implement an animation in my Android app using AnimatedVectorDrawableCompat, for compatibility for API >= 21.

我希望动画在持续时间内循环播放活动。我可以播放动画,并且在API> = 25时也可以正常播放。但是,当我在使用API​​ 21至24的设备或仿真器上运行该动画时,我只会看到一次动画。如果我在回调方法中设置一个断点,我也会看到它也执行回调,但是动画不会重复。

I want the animation to loop for the duration of the Activity. I'm able to play the animation, and it will also loop fine on API >= 25. But when I run it on devices or emulators with API 21 through 24 I only see the animation once. If I set a breakpoint inside the callback method, I see that it executes the callback too, but the animation does not repeat.

我发现动画正在运行

这是方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imageView = findViewById(R.id.image_view1);
    final AnimatedVectorDrawableCompat anim = AnimatedVectorDrawableCompat.create(this, R.drawable.avd_pass_inside);

    imageView.setImageDrawable(anim);

    anim.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
        @Override
        public void onAnimationEnd(Drawable drawable) {

            anim.start();
        }
    });
    anim.start();
}

根据我的阅读,使用Compat库应该使该功能适用​​于所有API级别从14开始,但我什至不必去那里,因为我的应用程序的其余部分要求将其设置为最低21。

From what I read, using the Compat library should make this work for all API levels from 14 and up, but I don't even have to go there, as the rest of my app has requirements that puts it at mimimum 21.

(最好是非hacky :))在这些API级别上保持一致工作的方法?是虫子吗?我错过了什么吗?

Is there some (preferably non-hacky :) ) way to make this work consistently across these API levels? Is it a bug? Did I miss something?

推荐答案

据我所知,这是系统与系统之间的细微差别。兼容版本。 Compat似乎在其动画被标记为结束之前调用了回调。因此,忽略对 start()的调用,因为它认为该调用尚未结束。

As far as I can see this is a subtle difference between the system & compat versions. Compat seems to call the callback before its animations have been flagged as having ended. So the call to start() is ignored because it thinks it hasn't ended.

解决方案是常见的破解方法:在动画结束后发布 Runnable 以启动它。

The solution is the usual hack: post a Runnable to start it when the animations have finished.

new Animatable2Compat.AnimationCallback() {
  @NonNull
  private final Handler fHandler = new Handler(Looper.getMainLooper());

  @Override
  public void onAnimationEnd(@NonNull Drawable drawable) {
    Animatable2Compat avd = (Animatable2Compat) drawable;
    fHandler.post(avd::start);
  }
};

这篇关于AnimatedVectorDrawableCompat使用回调循环动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆