简体   繁体   中英

How to set a cancel button in Progress Dialog?

I want to set a cancel button in my ProgressDialog . Below is my code:

myDialog = new ProgressDialog(BaseScreen.this);
myDialog.setMessage("Loading...");
myDialog.setCancelable(false);
myDialog.show();

I want to set a button with an onClickListener on this ProgressDialog . I tried with this code:

myDialog.setButton("Cancel", new OnClickListener() {        
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub          
        myDialog.dismiss();
    }
});

But it isn't working. I tried other similar listeners also, but still no success. How can I solve this problem?

The setButton method you are using is deprecated (although it should still work). Also, you might want to add the button before showing the dialog. Try:

myDialog = new ProgressDialog(BaseScreen.this);
myDialog.setMessage("Loading...");
myDialog.setCancelable(false);
myDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        myDialog.dismiss();//dismiss dialog
    }
});
myDialog.show();

Make sure you call myDialog.setButton before calling myDialog.show();
Also you can use myDialog.setButton("Cancel", (DialogInterface.OnClickListener) null); if you only need to close the dialog on button click.

check this

private void createCancelProgressDialog(String title, String message, String buttonText)
{
    cancelDialog = new ProgressDialog(this);
    cancelDialog.setTitle(title);
    cancelDialog.setMessage(message);
    cancelDialog.setButton(buttonText, new DialogInterface.OnClickListener() 
    {
        public void onClick(DialogInterface dialog, int which) 
        {
            // Use either finish() or return() to either close the activity or just the dialog
            return;
        }
    });
    cancelDialog.show();
}

then just use a simple call method from elsewhere in your activity

createCancelProgressDialog("Loading", "Please wait while activity is loading", "Cancel");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM