Android:datepickerdialog取消对话框而没有获取日期

时间:2015-06-29 15:26:39

标签: android android-dialog android-datepicker

在使用此代码段的片段类中:

Calendar c = Calendar.getInstance();
                int mYear = c.get(Calendar.YEAR);
                int mMonth = c.get(Calendar.MONTH);
                int mDay = c.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog dialog = new DatePickerDialog(getActivity(), datePickerListener, mYear, mMonth, mDay);
                dialog.setButton(DatePickerDialog.BUTTON_POSITIVE, "OK", dialog);
                dialog.setButton(DatePickerDialog.BUTTON_NEGATIVE, "ANNULLA", (DialogInterface.OnClickListener)null);
                dialog.show();


private DatePickerDialog.OnDateSetListener datePickerListener
            = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
            //Do whatever you want
            Log.d("DATEPICKER","La data presa è "+selectedDay+selectedMonth+selectedYear);
        }
    };

不幸的是,我点击了POSITIVE和NEGATIVE按钮的日期。当然,我只需要使用正面按钮来设置日期(但是,我在两个日志中都看到条目)。

2 个答案:

答案 0 :(得分:0)

如果查看 DatePickerDialog 的源代码(在API 16上测试),您会注意到总是在 onStop()中调用 onDateSet() 方法。 我重写了默认的正按钮行为,并实现了正按钮监听器而不是 onDateSet()

private class ReportDatePickerDialog extends DialogFragment implements android.content.DialogInterface.OnClickListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), null, initialYear, initialMonth, initialDay);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", ReportDatePickerDialog.this);
        return dialog;
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        ((DatePickerDialog)getDialog()).onClick(dialog, which);

        if (which != DialogInterface.BUTTON_POSITIVE) {
            return;
        }
        DatePicker datePicker = ((DatePickerDialog)getDialog()).getDatePicker();
        datePicker.getDayOfMonth();
        datePicker.getMonth();
        datePicker.getYear();
    }
}

我想最终在这种情况下创建自定义对话框窗口会更好。

答案 1 :(得分:-1)