简体   繁体   中英

Problem creating a custom dialog

I have a problem creating a custom dialog. But I don't find the failure. Hopefully anybody can help me ...

protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    switch (id) {
    case DIALOG_ABOUT_ID:
        dialog = buildAboutDialog();
        break;
    default:
        dialog = null;
    }
    return dialog;
}

...

public Dialog buildAboutDialog() {
    Context mContext = getApplicationContext();
    Dialog dialog = new Dialog(mContext);

    dialog.setContentView(R.layout.about_dialog);
    dialog.setTitle("About this application");

    return dialog;
}

Results in the following error:

12-30 19:27:02.593: ERROR/AndroidRuntime(383): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

I checked if the returned dialog == null - but it isn't.

I also tried the second way (inflater) described at http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog

I found out, that the dialog needs to be created with

Dialog dialog = new Dialog(this);

and not

Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);

I don't exactly know why. Perhaps anybody can explain it to me?

Dialog dialog = new Dialog(contex); dialog.setContentView(R.layout.help_content);

this works for me .. may be getapplicationcontext not getting context of the your main class.

As it turns out, Context of an activity is different then object returned by getApplicationContext(). This you can check by using logging, just output ActivityName.this and getApplicationContext.

The object returned by getApplicationContext is a global thing while context of an activity, well, belongs to that activity only.

Log.e(tag,""+ getApplicationContext());
Log.e(tag,""+CustomDialogActivity.this);

where CustomDialogActivity is my activity in which I want to show my dialog.

Dialogs require context of an activity and getApplicationContext() does not provide that. As written here (read comments) context of an activity is superset of getApplicationContext(). so It is a good thing to always pass context of an activity rather then the global context.

Also to answer ffleandro's comment of this page if you are inside onClick() you can use ActivityName.this to refer to activity. Hope this helps

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