Search code examples
androidandroid-alertdialogselecteditemselectedvalue

AlertDialog get selected value


This function create my alert dialog, and add two listeners, one to display the dialog when the users click on the EditText, and one to dismiss and fill the EditText when an AlertDialog value is selected.

I'm trying to retrieve the selected value of a AlertDialog, in order to fill an EditText.

I know where I can retrieve this value, but unfortunately, I don't know how.

public void addSex () {
    final AlertDialog.Builder builder = new AlertDialog.Builder(SignupActivity.this);
    builder.setTitle("Votre sexe").setItems(R.array.sex_array,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //Get dialog selected value
                }
            }
    );

    _sexText.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            AlertDialog dialog = builder.create();
            if (event.getAction() == MotionEvent.ACTION_DOWN)   dialog.show();
            return false;
        }
    });
}

Solution

  • Simply use which value to know selected element.

        @Override
    public void onClick(DialogInterface dialog, int which) {
                //Get dialog selected value
                String[] sexArray =  getResources().getStringArray(R.array.sex_array);
                _sexText.setText(sexArray[which]);    
    

    }