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

雨燕双飞 提交于 2019-11-26 12:25:28

问题


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

view.getContext()

But I can\'t figure out how to get the context inside onClick(DialogInterface v, int buttonId), the callback for a dialog\'s onClickListener

public class MainActivity extends Activity implements android.content.DialogInterface.OnClickListener

Is this possible?


回答1:


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.




回答2:


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.




回答3:


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



回答4:


inside setOnClickListener

decelare this below the class

Context context = this;

and use this context

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



来源:https://stackoverflow.com/questions/5447092/get-context-inside-onclickdialoginterface-v-int-buttonid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!