Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: int which in DialogInterface.OnClickListener() is -1

I don't understand why this is happening. I have the following code:

AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivityNew.this);

builder.setTitle("Title");
builder.setSingleChoiceItems(R.array.example_arrays, 1, null);              
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(SettingsActivityNew.this, "which: " + which, Toast.LENGTH_LONG).show();
    }
});
builder.show();

For some strange reason, the int which, keeps giving me -1. Why is this happening?

like image 571
Xander Avatar asked Apr 26 '13 18:04

Xander


1 Answers

From the doc :

Parameters
dialog  The dialog that received the click.
which   The button that was clicked (e.g. BUTTON1) or the position of the item clicked.


BUTTON_POSITIVE :
public static final int BUTTON_POSITIVE

Added in API level 3
The identifier for the positive button.

Constant Value: -1 (0xffffffff)

So that's not strange but totally normal. You get -1 each time because you clicked on the positiveButton of your dialog :)

like image 64
Alexis C. Avatar answered Nov 15 '22 03:11

Alexis C.