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?
You can reference an outer context when you define your
DialogInterface.OnClickListener
as an anonymous class. If you're in an activity you can useMyActivity.this
as the context.Edit - since your Activity is implementing
DialogInterface.OnClickListener
, you should be able to just usethis
as the context.If your DialogInterface is within MainActivity, then you can get the context using
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.
inside setOnClickListener
decelare this below the class
Context context = this;
and use this context
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
Here is how you do it in case you
Just simply,
dialogInterface
object and cast it toDialog
objectgetContext()
Example with DialogInterface.OnClickListener:
This will also work for the following interfaces as well, just use the first param
DialogInterface dialogInterface
and cast.