Dismiss DatePickerDialog on pressing back button

后端 未结 8 1943
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 12:29

On my view I have a button which when pressed pops up a DatePickerDialog. The poppedup dialog has a \"Done\" button. When I press that button the selected date is populated

8条回答
  •  鱼传尺愫
    2020-12-19 12:50

    Instead of implementing custom DatePickerDialog, you can implement custom OnClickListener for positive button:

    DatePickerDialog dateDialog = new DatePickerDialog(this, null, year, month, day);
    datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE,
        getResources().getString(R.string.text_done),
        new OnDoneClickListener(datePickerDialog));
    
    // <...>
    
    private class OnDoneClickListener implements DialogInterface.OnClickListener {
    
            private DatePickerDialog mPickerDialog;
    
            BirthDatePickerDialog(DatePickerDialog mPickerDialog) {
                this.mPickerDialog = mPickerDialog;
            }
    
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
                Calendar cal = Calendar.getInstance();
                DatePicker picker =  mPickerDialog.getDatePicker();
                cal.set(Calendar.YEAR, picker.getYear());
                cal.set(Calendar.MONTH, picker.getMonth());
                cal.set(Calendar.DAY_OF_MONTH, picker.getDayOfMonth());
                spinnerDateBirth.setText(dateFormat.format(cal.getTime()));
            }
    }
    

    Any of back or tap on empty area will dismiss the dialog with doing nothing.

提交回复
热议问题