Here is my code to initialize the AlertDialog
; buildexit
is AlertDialog.Builder
and exitalert
is AlertDialog
:
buildexit=new AlertDialog.Builder(this);
buildexit.setTitle("Exit?");
buildexit.setIcon(R.drawable.ic_action_warning);
buildexit.setMessage("Do you want to really exit?");
buildexit.setPositiveButton("Yes", this);
buildexit.setNegativeButton("No", this);
exitalert=buildexit.create();
I want to terminate the application using Activity.finish()
method when the user clicks the "Yes" button, if "No" is click nothing should happen, I have also implemented the android.content.DialogInterface.OnClickListener
interface, the method implemented is public void onClick(DialogInterface arg0, int arg1)
.
Thanks in advance.
I know this is an old question, but if you are like me, and ended here because you where googling, this is probably what you are looking for.
To avoid creating a new DialogInterface.onClickListener()
for each button, you can let the class implement AlertDialog.OnClickListener
, and then override public void onClick(DialogInterface dialog, int which)
.
The int which
in this method is the button that was clicked, or the position. See the Android Reference for more detailed information.
So if you want to check which button was clicked you can use a switch-case and look for the constants BUTTON_NEGATIVE
, BUTTON_NEUTRAL
, and BUTTON_POSITIVE
.
Example:
// skipping package and imports
public class TestActivity extends Activity implements AlertDialog.OnClickListener {
void createAndShowDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.title);
builder.setMessage(R.string.message);
builder.setPositiveButton(android.R.string.yes, this);
builder.setNeutralButton(android.R.string.cancel, this);
builder.setNegativeButton(android.R.string.no, this);
builder.create().show();
}
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case BUTTON_NEGATIVE:
// int which = -2
dialog.dismiss();
break;
case BUTTON_NEUTRAL:
// int which = -3
dialog.dismiss();
break;
case BUTTON_POSITIVE:
// int which = -1
TestActivity.this.finish();
dialog.dismiss();
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With