Is it possible to have an animated drawable?

后端 未结 7 1078
野的像风
野的像风 2020-12-28 10:34

Is it possible to create a drawable that has some sort of animation, whether it is a frame by frame animation, rotation, etc, that is defined as a xml drawable and can be re

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 11:00

    I take back to life this post just to post my solution with vector drawable:

    So you need 1 vector drawable in drawable resource (@drawable/ic_brush_24dp):

    
          <--- propertyName of animator
            
        
    
    

    Then you need your animator in animator resource folder (@animator/pendulum)

    
    
        
    
    

    Then you need your animated-vector in drawable resource (@drawable/test_anim_brush2):

    
    
        
    
    

    Then you need to extend ImageView (because that's the only way i found to start the animation)

    public class ImageView extends AppCompatImageView{
        public ImageView(Context context){
            super(context);
            init(context, null, 0);
        }
        public ImageView(Context context, AttributeSet attrs){
            super(context, attrs);
            init(context, attrs, 0);
        }
        public ImageView(Context context, AttributeSet attrs, int defStyleAttr){
            super(context, attrs, defStyleAttr);
            init(context, attrs, 0);
        }
        private void init(Context context, AttributeSet attrs, int defStyleAttr){
    
        }
    @Override
    protected void onAttachedToWindow(){
        super.onAttachedToWindow();
        Drawable d = getBackground();
        if(d instanceof AnimatedVectorDrawable){
            AnimatedVectorDrawable anim = (AnimatedVectorDrawable)d;
            anim.start(); 
        }        
    }
    @Override
    protected void onDetachedFromWindow(){
        super.onDetachedFromWindow();
        Drawable d = getBackground();
        if(d instanceof AnimatedVectorDrawable){
            AnimatedVectorDrawable anim = (AnimatedVectorDrawable)d;
            anim.stop();
        }
    }
    }
    

    And then add your imageView to your layout :

        
    

    Pro :

    • You can fully define your animation in xml with object animator (duration, interpolator, etc...)
    • Works with everything which accept drawable (as long as you add at good place the start animator)

    Con:

    • Works only with vector
    • Still need to add your custom start by extending class or whenever you think it is smart...

提交回复
热议问题