开发者

Showing simple message dialogs

开发者 https://www.devze.com 2022-12-14 04:50 出处:网络
In my activity, I\'d like to show simple info dialogs, stuff like: new AlertDialog.Builder(context).setMessage(message).show();

In my activity, I'd like to show simple info dialogs, stuff like:

new AlertDialog.Builder(context).setMessage(message).show();
开发者_如何学Python

if I do that, the dialog will leak when I rotate that phone (not to mention it will disappear as well, so the user may miss it). I can use the managed dialogs, but I'm not sure how you use it sensibly for these types of short messages? Looks like you have to do this:

showDialog(SOME_DLG_ID);
...
@Override
onCreateDialog(int id) {
    if (id == SOME_DLG_ID) {
        new AlertDialog.Builder(context).setMessage(message).show();
    }
}

there's no way to pass what the message should be into onCreateDialog since its an override method. I'd hate to make a member variable of the parent activity that just stores whatever the current message should be. How do you all do it?

Thanks


if I do that, the dialog will leak when I rotate that phone (not to mention it will disappear as well, so the user may miss it)

You can add

<activity 
    android:configChanges="orientation|keyboardHidden"
>

to your AndroidManifest.xml to prevent restarting the activity when the phone rotates. I am using it in my app and my AlertDialog survives the rotation of phone.


You can implement Activity.onPrepareDialog(int, Dialog) to switch out the message before the dialog is shown on the screen. So you could do something like:

@Override protected void onPrepareDialog(int id, Dialog dialog) {
    if (id == SOME_DLG_ID) {
        ((AlertDialog) dialog).setMessage(message);
    }
}

You'd still have to keep track of the message you're current showing in your activity, but at least this way, you're not creating a Dialog object for each message you want to show.


Using DialogFragment to manage the dialog ensures that it correctly handles lifecycle events such as when the user rotates the screen or presses the Back button.

0

精彩评论

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