简体   繁体   English

AnimatedVectorDrawableCompat使用回调循环动画

[英]AnimatedVectorDrawableCompat looping animation using callback

I'm trying to implement an animation in my Android app using AnimatedVectorDrawableCompat, for compatibility for API >= 21. 我正在尝试使用AnimatedVectorDrawableCompat在我的Android应用中实现动画,以实现与API> = 21的兼容性。

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. 我可以播放动画,并且在API> = 25时也可以正常播放。但是,当我在使用API​​ 21至24的设备或仿真器上运行该动画时,我只会看到一次动画。 If I set a breakpoint inside the callback method, I see that it executes the callback too, but the animation does not repeat. 如果我在回调方法中设置一个断点,则会看到它也执行回调,但是动画不会重复。

I find that the animation is running on a different thread, as it does not block UI. 我发现该动画在另一个线程上运行,因为它不会阻止UI。

This is the method: 这是方法:

@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();
}

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. 根据我的阅读,使用Compat库应该使该功能适用​​于14以上的所有API级别,但是我什至不必去那儿,因为我的应用程序的其余部分都要求至少达到21。

Is there some (preferably non-hacky :) ) way to make this work consistently across these API levels? 是否有某种方法(最好是非hacky :))可以在这些API级别上保持一致地工作? Is it a bug? 是虫子吗? Did I miss something? 我错过了什么?

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. Compat似乎在其动画被标记为结束之前调用了回调。 So the call to start() is ignored because it thinks it hasn't ended. 因此,对start()的调用将被忽略,因为它认为它尚未结束。

The solution is the usual hack: post a Runnable to start it when the animations have finished. 解决方法是通常的技巧:在动画结束后发布Runnable以启动它。

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);
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM