java 加载百分比时,Android ProgressBar 消息会发生变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12490965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:07:40  来源:igfitidea点击:

Android ProgressBar message change when percent is loaded

javaandroid

提问by Androyds

I am trying to add message when the progress bar loads on a specific percent. So when 10 percent is loaded a title or a message appear that something is loaded. I cant do it and it forcing to close. Any Ideas how to do it.

我正在尝试在进度条加载到特定百分比时添加消息。因此,当加载 10% 时,会出现一个标题或一条消息,表明已加载某些内容。我不能这样做,它被迫关闭。任何想法如何做到这一点。

Below is my sample code

下面是我的示例代码

  public void onClick(View v) {

        // prepare for a progress bar dialog
        progressBar = new ProgressDialog(v.getContext());
        progressBar.setCancelable(true);
        progressBar.setMessage("File downloading ...");
        progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressBar.setProgress(0);
        progressBar.setMax(100);
        progressBar.show();
        //getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        //reset progress bar status
        progressBarStatus = 0;
        //reset filesize
        fileSize = 0;

        new Thread(new Runnable() {
          public void run() {
            while (progressBarStatus < 100) {

              // process some tasks
              progressBarStatus = doSomeTasks();

              // your computer is too fast, sleep 1 second
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }

              // Update the progress bar
              progressBarHandler.post(new Runnable() {
                public void run() {
                  progressBar.setProgress(progressBarStatus);
                }
              });
            }

            // ok, file is downloaded,
            if (progressBarStatus >= 100) {

                // sleep 2 seconds, so that you can see the 100%
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // close the progress bar dialog
                progressBar.dismiss();
            }
          }
           }).start();

           }

            });

    }

// file download simulator... a really simple
public int doSomeTasks() {

    while (fileSize <= 1000000) {

        fileSize++;
        setProgressBarIndeterminate(true);
        if (fileSize == 100000) {
            progressBar.setMessage("10 percent loaded");
            return 10;
        } else if (fileSize == 200000) {
            progressBar.setMessage("20 percent loaded");
            return 20;
        } else if (fileSize == 300000) {
            progressBar.setMessage("30 percent loaded");
            return 30;
        }
        // ...add your own

    }

    return 100;

}

Thanks StackOverFlow users

感谢 StackOverFlow 用户

采纳答案by Priyank Patel

Try to update progress bar like below code...

尝试像下面的代码一样更新进度条...

//To use the AsyncTask, it must be subclassed  
private class LoadViewTask extends AsyncTask<Void, Integer, Void>  
{  
    //Before running code in separate thread  
    @Override  
    protected void onPreExecute()  
    {  
        //Create a new progress dialog  
        progressDialog = new ProgressDialog(LoadingScreenActivity.this);  
        //Set the progress dialog to display a horizontal progress bar  
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
        //Set the dialog title to 'Loading...'  
        progressDialog.setTitle("Loading...");  
        //Set the dialog message to 'Loading application View, please wait...'  
        progressDialog.setMessage("Loading application View, please wait...");  
        //This dialog can't be canceled by pressing the back key  
        progressDialog.setCancelable(false);  
        //This dialog isn't indeterminate  
        progressDialog.setIndeterminate(false);  
        //The maximum number of items is 100  
        progressDialog.setMax(100);  
        //Set the current progress to zero  
        progressDialog.setProgress(0);  
        //Display the progress dialog  
        progressDialog.show();  
    }  

    //The code to be executed in a background thread.  
    @Override  
    protected Void doInBackground(Void... params)  
    {  
        /* This is just a code that delays the thread execution 4 times, 
         * during 850 milliseconds and updates the current progress. This 
         * is where the code that is going to be executed on a background 
         * thread must be placed. 
         */  
        try  
        {  
            //Get the current thread's token  
            synchronized (this)  
            {  
                //Initialize an integer (that will act as a counter) to zero  
                int counter = 0;  
                //While the counter is smaller than four  
                while(counter <= 4)  
                {  
                    //Wait 850 milliseconds  
                    this.wait(850);  
                    //Increment the counter  
                    counter++;  
                    //Set the current progress.  
                    //This value is going to be passed to the onProgressUpdate() method.  
                    publishProgress(counter*25);  
                }  
            }  
        }  
        catch (InterruptedException e)  
        {  
            e.printStackTrace();  
        }  
        return null;  
    }  

    //Update the progress  
    @Override  
    protected void onProgressUpdate(Integer... values)  
    {  
        //set the current progress of the progress dialog  
        progressDialog.setProgress(values[0]);  
    }  

    //after executing the code in the thread  
    @Override  
    protected void onPostExecute(Void result)  
    {  
        //close the progress dialog  
        progressDialog.dismiss();  
        //initialize the View  
        setContentView(R.layout.main);  
    }  
}  

and call this AsyncTask where you want to show progress bar...

并在要显示进度条的位置调用此 AsyncTask ...

//Initialize a LoadViewTask object and call the execute() method  
new LoadViewTask().execute();    

回答by mdelolmo

Use AsynTaskinstead of basic threads. Within asynctask, use the callback onProgressUpdateto call progressBar.setProgress(progressBarStatus);

使用AsynTask而不是基本线程。在 asynctask 中,使用回调onProgressUpdate来调用 progressBar.setProgress(progressBarStatus);

You only can access UI elements from the main thread.

您只能从主线程访问 UI 元素。