Get context inside onClick(DialogInterface v, int buttonId)?
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.
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.
Here is how you do it in case you
- do not want to have any anonymous class usage
- or having your activity/fragment implement the interface directly.
Just simply,
- use
dialogInterface
object and cast it toDialog
object - 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