Get context inside onClick(DialogInterface v, int buttonId)?

前端 未结 4 1334
悲哀的现实
悲哀的现实 2020-11-29 03:36

Getting the context inside onClick(View view), the callback for a button\'s onClickListener(), is easy:

view.getContext()


        
相关标签:
4条回答
  • 2020-11-29 03:48

    You can reference an outer context when you define your DialogInterface.OnClickListener as an anonymous class. If you're in an activity you can use MyActivity.this as the context.

    Edit - since your Activity is implementing DialogInterface.OnClickListener, you should be able to just use this as the context.

    0 讨论(0)
  • 2020-11-29 03:52

    If your DialogInterface is within MainActivity, then you can get the context using

    MainActivity.this.getActivityContext();

    Btw You can also implement the DialogInterface (in your code sample, you have written implements twice) and the same statement can be used to get the activity context.

    0 讨论(0)
  • 2020-11-29 03:57

    Here is how you do it in case you

    1. do not want to have any anonymous class usage
    2. or having your activity/fragment implement the interface directly.

    Just simply,

    1. use dialogInterface object and cast it to Dialog object
    2. then call getContext()

    Example with DialogInterface.OnClickListener:

    DialogInterface.OnClickListener foo = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int which) {
            Dialog dialog  = (Dialog) dialogInterface;
            Context context = dialog.getContext();
            // do some work with context
        }
    };
    

    This will also work for the following interfaces as well, just use the first param DialogInterface dialogInterface and cast.

    • DialogInterface.OnCancelListener
    • DialogInterface.OnDismissListener
    • DialogInterface.OnKeyListener
    • DialogInterface.OnMultiChoiceClickListener
    • DialogInterface.OnShowListener
    0 讨论(0)
  • 2020-11-29 04:01

    inside setOnClickListener

    decelare this below the class

    Context context = this;

    and use this context

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

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