Ad

How To Animate The Level Meter Bar?

I am fairly new to Java and android studio. I would like to animate my bar which I created with random value. I have created customView with android studio and drawn a canvas rectangle. Next step is feed some random values and animate the bar. I acheived this feat with (Math.random) in JavaScript.

    public class CustomView extends View {

    private Rect rect;
    private Paint paint;
    int radius;

    public CustomView(Context context){
        super(context);
        init(null);
    }

    public CustomView(Context context, AttributeSet attrs){
        super(context, attrs);
        init(attrs);
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr){
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }

    private void init(@Nullable AttributeSet set){
        rect = new Rect();
        // the flag is more pixelated
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        postInvalidate();
    }

    //drawing a canvas
    @Override
    protected void onDraw(Canvas canvas){
        int viewWidth = getWidth();
        int viewHeight = getHeight();

        int leftTopX = viewWidth - 750;
        int leftTopY = viewHeight - 750;

        int rightBotX = viewWidth + 150;
        int rightBotY = viewHeight + 150;

        paint.setColor(Color.MAGENTA);
        canvas.drawRect(leftTopX,leftTopY, rightBotX,rightBotY,paint);
        paint.setColor(Color.GREEN);

    }
}

This is what I have achieved so far by now.But how can I animate bar with Java ?

enter image description here

Ad

Answer

Try this -
 I used it with seekbar. You can use it for your view. As per your case. You should Progressbar or Seekbar.

seekbar = ((CustomSeekbar) findViewById(R.id.customSeekBar));

       seekbar.setMax(2600);

final ObjectAnimator animation = ObjectAnimator.ofInt(seekbar, "progress", 0, 800;
      animation.setDuration(1500);
      animation.setInterpolator(new DecelerateInterpolator());
      animation.start();
      seekbar.clearAnimation();

Here 0 is the starting value and 800 is the max value. Please change is as per your requirement.
Ad
source: stackoverflow.com
Ad