有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

关于Android进度条工作的java

我对安卓中的进度条有疑问。我还没有实施它,但由于时间不够,我想确保在实施时,我最好弄清楚将要发生什么以及为什么

dialog = new ProgressDialog(this);
        dialog.setCancelable(true);
        dialog.setMessage("Loading...");
        // set the progress to be horizontal
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // reset the bar to the default value of 0
        dialog.setProgress(0);

        // get the maximum value
        EditText max = (EditText) findViewById(R.id.maximum);
        // convert the text value to a integer
        int maximum = Integer.parseInt(max.getText().toString());
        // set the maximum value
        dialog.setMax(maximum);
        // display the progressbar
        dialog.show();

        // create a thread for updating the progress bar
        Thread background = new Thread (new Runnable() {
           public void run() {
               try {
                   // enter the code to be run while displaying the progressbar.
                   //
                   // This example is just going to increment the progress bar:
                   // So keep running until the progress value reaches maximum value
                   while (dialog.getProgress()<= dialog.getMax()) {
                       // wait 500ms between each update
                       Thread.sleep(500);

                       // active the update handler
                       progressHandler.sendMessage(progressHandler.obtainMessage());
                   }
               } catch (java.lang.InterruptedException e) {
                   // if something fails do something smart
               }
           }
        });

        // start the background thread
        background.start();

    }

    // handler for the background updating
    Handler progressHandler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.incrementProgressBy(increment);
        }
    };

这是我从某处获取的上述代码。。。正如这段代码所说,我必须将我的实际代码保持在下面,尝试保持进度条运行。。我的疑问是,我的代码很长,包含嵌套的for循环(用所有这些位和字节解析整个文件)。。如果我将冗长的过程保留在该部分,它如何更新进度条,直到完成任务? 我是不是错过了一些概念?请解释我如何保持进程运行并更新进度条


共 (1) 个答案

  1. # 1 楼答案

    您应该使用AsynTask并在其onPreExecute()方法中显示ProgreesBar,并在其onPostExecute()方法中关闭ProgressBar。用doInBackground()方法加载所有内容。此外,要更新ProgressBar,请使用onProgressUpdate()

    这将有助于:http://developer.android.com/reference/android/os/AsyncTask.html