Problem creating a custom dialog

前端 未结 3 1522
傲寒
傲寒 2021-01-16 14:59

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) {
    Di         


        
相关标签:
3条回答
  • 2021-01-16 15:23

    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.

    0 讨论(0)
  • 2021-01-16 15:25

    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?

    0 讨论(0)
  • 2021-01-16 15:25

    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

    0 讨论(0)
提交回复
热议问题