AnimationDrawable not playing

前端 未结 6 741
独厮守ぢ
独厮守ぢ 2020-12-31 00:22

So I want my animation to start as soon as the activity is created, but for some reason no matter what I try will get it to start. I can get it to start by having a click ev

6条回答
  •  生来不讨喜
    2020-12-31 00:33

    My solution for playing animations while they are visible. It let you declare (in xml layout) and forget.

    class AnimatedImageView extends ImageView {
        // required constructors omitted for clarity 
    
        private void updateAnimationsState() {
            boolean running = getVisibility() == View.VISIBLE && hasWindowFocus();
            updateAnimationState(getDrawable(), running);
            updateAnimationState(getBackground(), running);
        }
    
        private void updateAnimationState(Drawable drawable, boolean running) {
            if(drawable instanceof AnimationDrawable) {
                AnimationDrawable animationDrawable = (AnimationDrawable) drawable;
                if(running) {
                    animationDrawable.start();
                } else {
                    animationDrawable.stop();
                }
            }
        }
    
        @Override
        protected void onVisibilityChanged(View changedView, int visibility) {
            super.onVisibilityChanged(changedView, visibility);
            updateAnimationsState();
        }
    
        @Override
        public void onWindowFocusChanged(boolean hasWindowFocus) {
            super.onWindowFocusChanged(hasWindowFocus);
            updateAnimationsState();
        }
    }
    

    If you setup drawable from code, then you should override appropriate set*() methods and call updateAnimationsState() from there.

提交回复
热议问题