Search code examples
androidandroid-dialogandroid-datepicker

DatePicker dialog and button => click twice to open


i create a dialog in my onCreate method in my normal activity:

 datePicker = new DatePickerDialog(this, this, cal.get(YEAR),
                    cal.get(MONTH), cal.get(DAY_OF_MONTH));

then i call a button listener :

Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                datePicker.show();
                Log.e("tag", "Passage dans le click");

            }
        });

when cancel =>

  1. when i click this button one time, the datepicker showing.
  2. i click cancel on the dialog
  3. i click on the button second time, the datepicker showing

when OK =>

  1. when i click this button one time, the datepicker showing.
  2. i click OK on the dialog
  3. i click on the button second time, the datepicker NOT showing

howewer if i write twice Datepicker.show(), that work :

 Button button = (Button) findViewById(R.id.button);
            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    datePicker.show();
                     datePicker.show();
                    Log.e("tag", "Passage dans le click");

                }
            });

Solution

  • you can try below code... A dialog object is every time create and it would be showing every time. hope it will work.

    Button button = (Button) findViewById(R.id.button);
            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
    
           datePicker = new DatePickerDialog(this, this, cal.get(YEAR), cal.get(MONTH), cal.get(DAY_OF_MONTH));
    
                    datePicker.show();
                    Log.e("tag", "Passage dans le click");
    
                }
            });