Animate ProgressBar update in Android

后端 未结 13 1147
悲哀的现实
悲哀的现实 2020-11-28 04:04

I am using a ProgressBar in my application which I update in onProgressUpdate of an AsyncTask. So far so good.

What I want to do is to animate the prog

13条回答
  •  有刺的猬
    2020-11-28 04:11

    My solution with custom ProgressBar. You can specify animation (animationLength) legth and "smoothness" (animationSmoothness) using attributes (when you use it in XML layout)

    AnimatedProgressBar.java

    public class AnimatedProgressBar extends ProgressBar {
    private static final String TAG = "AnimatedProgressBar";
    
    private static final int BASE_ANIMATION_DURATION = 1000;
    private static final int BASE_PROGRESS_SMOOTHNESS = 50;
    
    private int animationDuration = BASE_ANIMATION_DURATION;
    private int animationSmoothness = BASE_PROGRESS_SMOOTHNESS;
    
    public AnimatedProgressBar(Context context) {
        super(context);
        init();
    }
    
    public AnimatedProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        obtainAnimationAttributes(attrs);
        init();
    }
    
    public AnimatedProgressBar(Context context, AttributeSet attrs, int theme) {
        super(context, attrs, theme);
        obtainAnimationAttributes(attrs);
        init();
    }
    
    private void obtainAnimationAttributes(AttributeSet attrs) {
        for(int i = 0; i < attrs.getAttributeCount(); i++) {
            String name = attrs.getAttributeName(i);
    
            if (name.equals("animationDuration")) {
                animationDuration = attrs.getAttributeIntValue(i, BASE_ANIMATION_DURATION);
            } else if (name.equals("animationSmoothness")) {
                animationSmoothness = attrs.getAttributeIntValue(i, BASE_PROGRESS_SMOOTHNESS);
            }
        }
    }
    
    private void init() {
    
    }
    
    @Override
    public synchronized void setMax(int max) {
        super.setMax(max * animationSmoothness);
    }
    
    public void makeProgress(int progress) {
        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(this, "progress", progress * animationSmoothness);
        objectAnimator.setDuration(animationDuration);
        objectAnimator.setInterpolator(new DecelerateInterpolator());
        objectAnimator.start();
    }}
    

    values/attrs.xml:

    
    
        
            
            
        
    
    

提交回复
热议问题