Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DialogInterface's onClick() method

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.

like image 609
Ved Avatar asked Nov 29 '22 00:11

Ved


1 Answers

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;
    }
}
like image 139
Kyrremann Avatar answered Dec 04 '22 12:12

Kyrremann