有 Java 编程相关的问题?

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

java ProgressBar显示方法中正在完成的工作的进度,如何

我试图实现一个ProgressBar,这样当我的应用程序变得稍微空闲时(由于试图计算一个有很多东西在进行的方法),它应该显示该方法的完成进度,这是一个布尔方法,应该在最后返回true 所以现在我很困惑,当一个进程(作为一个整数值)不是一个整数返回类型的方法时,我该如何监控它

我尝试了很多不同的方法,但当我使用处理程序时,我不知道如何将其编码为:

。。当这个带有progressbar处理程序的线程完成时,method=true,显示数据

我将展示我在做什么,即使我的逻辑现在可能不太正常

private ProgressDialog progressBar;
private int percentageStatus = 0;
private Handler progressBarHandler = new Handler();


    Thread loadingBar = new Thread(new Runnable() {

            public void run() {


                while(percentageStatus <= 100)
                {
                    percentageStatus++;

                    try 
                    {
                        Thread.sleep(20);
                    } 
                    catch (InterruptedException e) 
                    {
                        e.printStackTrace();
                    }


                    progressBarHandler.post(new Runnable() {

                        public void run() 
                        {
                            progressBar.setProgress(percentageStatus);

                            Log.i("TESTS", "check..." + percentageStatus);
                        }
                    });
                }

                if (percentageStatus >= 100) 
                {


                    try 
                    {
                        Thread.sleep(100);
                    } 
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }

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

                    progressBar.cancel();
                }
            }
        });



        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);

            progressBar = new ProgressDialog(this);
            progressBar.setCancelable(true);
            progressBar.setMessage("Loading...");
            progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressBar.setProgress(0);
            progressBar.setMax(100);
            progressBar.show();

            loadingBar.start();


            while(doWaitTask() < 100)
            {
                doWaitTask();
            }

            programCreated = true;

            if(programCreated == true)      
            {   
                data = (TextView)findViewById(R.id.debug);      
                MyAsyncTask task = new  MyAsyncTask();
                task.execute(); //this is an async task which just appends some text to a TextView
            }

        }



public int doWaitTask() {

        while (loadingValue <= 10000) {

            loadingValue++;
        }

        return 100;
    }

“doWaitTask()”只是我用来模拟某些正在完成的工作的方法(用于SSSCCEE)

总结一下:当progressBar显示和更新进度时,我试图使屏幕空白,没有文本,一旦进度完成,它应该在进度完成后显示屏幕上的内容(因此我试图让它像加载条一样工作)

使用异步任务会更好吗?在这种情况下又是怎样的呢


共 (3) 个答案

  1. # 1 楼答案

    我要求你使用异步任务。您可以在下面找到我们如何使用它的示例:

    1. 首先,我们需要创建活动的界面(在我的示例中,我们将使用按钮和进度条):

      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/myLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent" >
      <Button
          android:id="@+id/btDoTask"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentLeft="true"
          android:layout_alignParentTop="true"
          android:layout_marginLeft="102dp"
          android:layout_marginTop="24dp"
          android:text="Do Async Task" />
      <ProgressBar
          android:id="@+id/pbAsyncBackgroundTraitement"
          style="?android:attr/progressBarStyleHorizontal"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentLeft="true"
          android:layout_alignParentRight="true"
          android:layout_below="@+id/button1"
          android:layout_marginTop="20dp"    />  
      </RelativeLayout>
      
    2. 其次,我们将实现自定义异步任务:

      package com.exemple.devhacksecuretest.asynctaskwithprogressbar;
      import com.example.devhacksecuretest.R;
      import android.app.Activity;
      import android.os.AsyncTask;
      import android.util.Log;
      import android.view.View;
      import android.widget.ProgressBar;
      import android.widget.Toast;
      
      public class CustomAsyncTask extends AsyncTask<String, Integer, Integer>{
          private Activity  mContext;
          private ProgressBar pbAsyncBackgroundTraitement;
      
          public CustomAsyncTask(Activity  mContext) {
              super();
              this.mContext = mContext;
          }
      
      
          /* function which is called first */
          @Override
          protected void onPreExecute() {
              this.pbAsyncBackgroundTraitement = (ProgressBar) mContext.findViewById(R.id.pbAsyncBackgroundTraitement);
              this.pbAsyncBackgroundTraitement.setVisibility(View.VISIBLE);
              super.onPreExecute();
          }
      
      
          /* function work on background */
          @Override
          protected Integer doInBackground(String... params) {
      
              // Here you have to put what you want to do
              for (int i = 0; i< params[0].length(); i++){
                  try {
                      Thread.sleep(100);
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
      
                  int progress = (i * 100 / params[0].length());
                  Log.i("test", " progress : " + progress);
      
                  //  call onProgressUpdate()
                  publishProgress(progress);
              }
              return null;
          }
      
      
          /* function to update the ProgressBar */
          @Override
          protected void onProgressUpdate(Integer... values) {
      
              // update the progress bar
              this.pbAsyncBackgroundTraitement.setProgress(values[0]);
              super.onProgressUpdate(values);
          }
      
          /* function called after work on background function is over */
          @Override
          protected void onPostExecute(Integer result) {
      
              // The work is done, you can do an action like create an activity or set invisible some UI components
              this.pbAsyncBackgroundTraitement.setVisibility(View.GONE);
              Toast.makeText(this.mContext, "Work is over... Do what you want now...bla bla bla", Toast.LENGTH_LONG).show();
              super.onPostExecute(result);
          }
      
      }
      

      三,。最后,在包含按钮和进度条的主活动中,只需在OnClick按钮中添加以下行:

       public void onClick(View v) {
          // TODO Auto-generated method stub
          switch (v.getId()){
          case R.id.btDoTask:
      
              // Call CustomAsyncTask
              CustomAsyncTask myCustomTask = new CustomAsyncTask(this);
      
              // Execute task, we give it the parameter to work with
              myCustomTask.execute("Params to execute in background");
              break;
          }
      }
      
  2. # 2 楼答案

    我已经为我想要的做了一个变通,一个非常“确定”的方式

    首先,我有一个登录类

    公共类登录扩展活动实现OnClickListener

    static String port_text;
    static String ip_text;
    static int portnum;
    
    public void onClick(View v) {
    
        if(v.getId() == btn1.getId())
        {
            port_text = port.getText().toString();
            ip_text = ip.getText().toString();
    
            portnum = Integer.parseInt(port_text);  
    
    
            /**.....exception handling operations...... 
    
            **/
    
                Intent myIntent = new Intent(Login.this, Loader.class);
    
                startActivity(myIntent);        
    
        }
    }
    

    我打算进入一个加载屏幕,该屏幕专门用于等待所需的类加载

    公共类加载器扩展登录

    private ProgressDialog progressBar;
    
        static LoadingScreen instance;
    
    
        static LoadingScreen getInstance()
        {
            return instance;
        }
    
    
        public int getPort()
        {
            return portnum;
        }
    
        public String getIP()
        {
            return ip_text;
        }
    
    
        @Override
        public void onCreate(Bundle savedInstanceState){
    
            super.onCreate(savedInstanceState); 
            setContentView(R.layout.blank_activity);
    
            instance = this;
    
            progressBar = new ProgressDialog(this);
            progressBar.setCancelable(true);
            progressBar.setMessage("Loading...");
            progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
            progressBar.setIndeterminate(true);
            progressBar.show();
    
    
            final Intent mainIntent = new Intent(LoadingScreen.this, MainActivity.class); 
    
            new Handler().postDelayed(new Runnable(){ 
    
                @Override 
                public void run() { 
    
                    try 
                    {
                        Thread.sleep(1000);
                    } 
                    catch (InterruptedException e) 
                    {
                        e.printStackTrace();
                    }
    
                    startActivity(mainIntent);              
                    finish(); 
    
                    progressBar.cancel();
                } 
            }, 2000);
        }
    

    我必须创建一个单例来从“Login”超类获取静态变量数据,原因是,如果我在处理程序中启动了一个intent bundle,那么数据将无法在所需的类中检索,因此,在本例中,我使用了一个postdayed处理程序,它启动一个Intent,并在处理程序结束之前等待一段指定的时间(这个时间值可以通过反复试验获得),这样我就避免了当活动试图加载时出现黑屏

    公共类MainActivity扩展了FragmentActivity

        Loader ls = Loader.getInstance();
    
        int port_num = ls.getPort();
        String ip_address = ls.getIP();
    
    /*  ....do operations with the port num and IP address...*/
    
  3. # 3 楼答案

    你不应该只是人为地弥补已经取得的进展。完成的进度要么太慢(这将导致任务完成得太早),要么太快(这将导致进度条长时间显示100%)

    如果你知道所取得的实际进展,那么你应该使用它。如果处理需要N个步骤(长度大致相同),并且您已经完成了x个步骤,那么您的百分比为100*x/N。使用AsyncTask包含逻辑是一个很好的方法,可以让UI线程保持响应

    另一方面,如果您不知道已经取得了多少进展,那么您应该使用“不确定模式”进度条。引用ProgressBar JavaDoc的话:

    In indeterminate mode, the progress bar shows a cyclic animation without an indication of progress. This mode is used by applications when the length of the task is unknown. The indeterminate progress bar can be either a spinning wheel or a horizontal bar.