Animate ProgressBar update in Android

后端 未结 13 1150
悲哀的现实
悲哀的现实 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:19

    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:

    public class MahClass extends AsyncTask {
    
        @Override
        protected Void doInBackground(Void... params) {
            while (progressBar.getProgress() < progress) {
                publishProgress();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        @Override
        protected void onProgressUpdate(Void... values) {
            progressBar.incrementProgressBy(1);
        }
    }
    

    AsyncTask might seem complicated at first, but it is really efficient for many different tasks, or as specified in the Android API:

    "AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers."

提交回复
热议问题