单击按钮上的进度条

kus*_*usi 0 android onclick progress-bar

在我的应用程序中,只需单击一个按钮,应用程序就可以进行一些处理,通过网络发送一些数据然后停止.由于需要一些时间,我试着加入进度条.进度条的代码位于按钮的onclick侦听器的开头.在进度条形码之后,通过网络处理和发送数据.但进度条根本不可见.我是否需要在单独的线程中显示进度条?

这就是我用来显示进度条的内容

final ProgressDialog pd=new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setMessage("Please wait..");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
Run Code Online (Sandbox Code Playgroud)

Pra*_*tik 5

使用用于在后台进行处理的AsyncTask类,您还可以在那里显示进度条

以下是AsyncTask的简单代码片段

class BackgroundProcess extends AsyncTask<Void,Void,Void>{
   private ProgressDialog progress;
   public doInBackground(Void...arg){
        publishProgress();
        // do your processing here like sending data or downloading etc.
   }
   @Override
   protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
    progress = ProgressDialog.show(YourActivity.this, "", "Wait...");       
   }
   @Override
   protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    if(progress!=null)
        progress.dismiss();
    progress = null;
   }
}
Run Code Online (Sandbox Code Playgroud)

现在按照这种方式在按钮onclick监听器中初始化并执行它

new BackgroundProcess().execute();
Run Code Online (Sandbox Code Playgroud)

现在progressdialog将被发布并出现在屏幕上,当进程完成后,然后从onPostExecute()中解除进度对话框