Akshay
Akshay

Reputation: 23

Add smooth animation between two consecutive progress points in a seekbar

I am trying to smoothly animate the seekbar when setting progress, say progress from 1 to 2.

I have tried setting the animation using an ObjectAnimator with an interpolator but that only moves through the progress points. Setting the max value of the seekbar to a high value for smoother scroll is not an option.

I did find a version of setProgress - setProgress (int progress, boolean animate) which animates the seekbar how I would like, between consecutive progress points.

But it is not possible to set duration or customize the animation like an ObjectAnimator would.

Any solutions as to how to achieve a result where I can customize the properties of such an animation?

Upvotes: 2

Views: 1744

Answers (1)

BenjyTec
BenjyTec

Reputation: 10375

The solution is to set the max value of the ProgressBar very high. To ensure that the user still only can pick values in bigger steps, set a onSeekBarChangeListener and round the input value and set this value as the progress.

Say you have a ProgressBar where the user can pick between 0 to 10. At the beginning, 2 is selected.

seekBar = findViewById(R.id.seekBar);
seekBar.setMax(10*100);
seekBar.setProgress(2*100);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
        //if the progress change is triggered by the user, update progress to closest value
        if (fromUser) {
            seekBar.setProgress(Math.round((float)progress / 100) * 100);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
});

Then trigger the animation via ObjectAnimator:

public void animateSeekbar(int toProgress) {
    ObjectAnimator animation = ObjectAnimator.ofInt(seekBar, "progress", toProgress*100);
    animation.setDuration(1000);
    animation.start();
}

Now the user can only pick a few values, and the animation still can be done smoothly. Hope this helps you.

Upvotes: 1

Related Questions