开发者

How to dismiss a dialog from another method

开发者 https://www.devze.com 2023-02-22 03:25 出处:网络
I have created a dialog which can be called from anywhere by supplying a title and message as follows:

I have created a dialog which can be called from anywhere by supplying a title and message as follows:

public void alertbox(String title, String mymessage)
{   new AlertDialog.Builder(this)
        .setTitle(title)
        .setMessage(mymessage)
        .setNeutralButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() 
                {   public void onClick(DialogInterface dialog, int whichButton) {}
                })
        .show();
}

But I get a lockup when I try to dismiss the dialog from another method:

private void doCheck() {
    alertbox("status", getString(R.string.checking_license));
    mChecker.checkAccess(mLicenseCheckerCallback);

    alertbox.dismiss();
} 

It is the alert开发者_如何学JAVAbox.dismiss(); statement that causes the crash. Any ideas how to properly do this?


I came across this issue also and wanted to share my solution for anyone who chooses not to use the above method.

Firstly I defined my AlertDialog along with the class variables:

private AlertDialog alertbox;

Then I initiate the AlertDialog wherever it is required:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("title");
builder.setMessage("message");

alertbox = builder.create();
alertbox.show();

Finally, due to orginally defining the AlertDialog as an instance variable, I can close the AlertDialog through any methods within the class.

private void dismissAlert()
{
    alertbox.dismiss()
}


It could be as simple as calling runOnUiThread:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        alertbox.dismiss();
    }
});

if you are on the wrong thread. Although with your additional details, the problem is more simple. To give away the punchline:

public AlertDialog alertbox(String title, String mymessage) {   
    return new AlertDialog.Builder(this)
        .setTitle(title)
        .setMessage(mymessage)
        .setNeutralButton(android.R.string.cancel,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {}
            })
        .show();
}

and:

private void doCheck() {
    AlertDialog alert = alertbox("status", getString(R.string.checking_license));
    mChecker.checkAccess(mLicenseCheckerCallback);
    alert.dismiss();
}

Although you probably don't want to both show and dismiss the dialog in the same method. Do you see how the above code is at least saving a reference to the dialog so that you can dismiss it later?


I would have alertBox return the dialog like so

public AlertDialog alertbox(String title, String mymessage)

Then wherever you call it you can keep reference to the returned dialog and dismiss it as needed.

0

精彩评论

暂无评论...
验证码 换一张
取 消