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 progress update, so that it does not just "jump" to the value but smoothly moves to it.
I tried doing so running the following code:
this.runOnUiThread(new Runnable() {
@Override
public void run() {
while (progressBar.getProgress() < progress) {
progressBar.incrementProgressBy(1);
progressBar.invalidate();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
The problem is that the progress bar does not update its state until it finished its final value (progress variable). All states in between are not displayed on the screen. Calling progressBar.invalidate() didn't help either.
Any ideas? Thanks!
You could try using a handler / runnable instead...
EDIT: While my answer works, Eli Konkys answer is better. Use it.
if your thread runs on the UI thread then it must surrender the UI thread to give the views a chance to update. Currently you tell the progress bar "update to 1, update to 2, update to 3" without ever releasing the UI-thread so it actually can update.
The best way to solve this problem is to use Asynctask, it has native methods that runs both on and off the UI thread:
AsyncTask might seem complicated at first, but it is really efficient for many different tasks, or as specified in the Android API:
A Kotlin way of doing this
I used android Animation for this:
and call it like so:
Note: if from and to value are too low to produce smooth animation just multiply them by a 100 or so. If you do so, don't forget to multiply setMax(..) as well.
Here is an improved version of @Eli Konky solution:
And usage:
I use an ObjectAnimator