Istiaque Ahmed
Istiaque Ahmed

Reputation: 6498

android dialog button OnclickListener - how is the id value determined

Simple code inside MainActivity.java to create an alert dialog :

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

                alertDialogBuilder.setTitle("Your Title")
                .setMessage("Click yes or exit")
                .setCancelable(false)
                .setIcon(R.drawable.icon)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id ){

                        Log.v(" yes id =  ",id+"");

                        MainActivity.this.finish();

                    }

                })
                .setNegativeButton("No", new DialogInterface.OnClickListener(){

                    public void onClick(DialogInterface dialog, int id){

                        Log.v(" no id =  ",id+"");

                        dialog.cancel();
                    }

               });



                AlertDialog alertDialog= alertDialogBuilder.create();

                alertDialog.show();

Clicking on the yes button shows in logcat : yes id =: -1 and the no button similarly shows : no id =: -2

So how is the value of the argument id inside onClick method determined ?

Upvotes: 0

Views: 3018

Answers (3)

pasignature
pasignature

Reputation: 585

I believe the above Dialog Button constants are all deprecated now.

Upvotes: 0

Paresh
Paresh

Reputation: 6857

Pasting the code of DialogInterface class -

interface OnClickListener {
        /**
         * This method will be invoked when a button in the dialog is clicked.
         * 
         * @param dialog The dialog that received the click.
         * @param which The button that was clicked (e.g.
         *            {@link DialogInterface#BUTTON1}) or the position
         *            of the item clicked.
         */
        /* TODO: Change to use BUTTON_POSITIVE after API council */
        public void onClick(DialogInterface dialog, int which);
    }

public static final int BUTTON1 = BUTTON_POSITIVE;
public static final int BUTTON_POSITIVE = -1;

That's why, It is returning -1!! because you are clicking positive button and BUTTON_POSITIVE = -1

Upvotes: 5

Akshay Panchal
Akshay Panchal

Reputation: 695

Dialog Buttons constants are as follows

int BUTTON_NEGATIVE = -2;
int BUTTON_NEUTRAL = -3;
int BUTTON_POSITIVE = -1;

So you can just compare your id with these constants (Access constants as below)

Dialog.BUTTON_NEGATIVE;
Dialog.BUTTON_POSITIVE;
Dialog.BUTTON_NEUTRAL;

Upvotes: 3

Related Questions