Use Asynctask to display a ProgressBar in Android

后端 未结 5 1539
暖寄归人
暖寄归人 2021-01-24 15:59

I am trying to do display a ProgressBar.

I am an Android beginner.

When I press the button, the task should be running in the background, but it does not display

相关标签:
5条回答
  • 2021-01-24 16:17

    You are not calling dialog.show() in onPreExecute method of your AsyncTask.

    0 讨论(0)
  • 2021-01-24 16:22

    Use ProgressDialog. You don't need any layout in this case.

    ProgressDialog progressDialog = new ProgressDialog(context);
    

    in onPreExecute show it

    progressDialog.show();
    

    and in onPostExecute dissmiss it

    progressDialog.dismiss();
    
    0 讨论(0)
  • 2021-01-24 16:23

    Add to OnPostExecute method :

    pg.setVisibility(View.INVISIBLE);
    

    Add to onPreExecute method :

    pg.setVisibility(View.VISIBLE);
    

    and in Layout file you should add to progress bar :

    android:visibility="invisible" 
    
    0 讨论(0)
  • 2021-01-24 16:27

    You created the dialog but not showing it anywhere. Your onPreExecute() should look like:

    @Override
    protected void onPreExecute() {
    
        super.onPreExecute();
        // create dialog
        dialog=new Dialog(context);
        dialog.setCancelable(true);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.pogressdialog);
        txtprogrss=(TextView) dialog.findViewById(R.id.txtProgress);
        progress=(ProgressBar)dialog.findViewById(R.id.progressBar2);
        btnCancel=(Button)dialog.findViewById(R.id.btnProgress);
    
        btnCancel.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
    
                MyTask.this.cancel(true);
                dialog.dismiss();  //On button click cancel AsyncTask and dismiss dialog
            }
        });
        dialog.show();  //Show the dialog
    }
    

    You also need to dismiss the dialog when clicked on btnCancel.

    0 讨论(0)
  • 2021-01-24 16:29

    You forgot to call dialog.show() at the onPreExecute()

    0 讨论(0)
提交回复
热议问题