Use Asynctask to display a ProgressBar in Android

对着背影说爱祢 提交于 2019-12-02 05:07:43

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

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

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();

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" 

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!