Android Progressbar not updating

前端 未结 5 1322
情深已故
情深已故 2021-01-28 22:33

i got a problem in updating progress bar. I am updating progress bar in separate Thread and the variable on which the progressbar progress is depending(which is a class variable

5条回答
  •  情话喂你
    2021-01-28 23:27

    Use AsyncTask, there is also an example in this document to answer your need.

    This code from AsyncTask actually do what you want to accomplish.

    private class DownloadFilesTask extends AsyncTask {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
    
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
    
     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
      }
    

    Only thing you need to change setProgressPercent() to your method name of progress bar value change. You could delete onPostExecute method AFAIK if you don't need it. Try to use AsyncTask instead of java Thread since AsyncTask provide methods already for your need while you need to write them if you use Thread instead.

提交回复
热议问题