选择日期后,日期选择器应在Android中关闭而不点击“正常”按钮

时间:2016-07-26 09:38:39

标签: java android date android-studio datepicker

我在android中使用默认的日期选择器,现在我要关闭对话框 选择日期后,日期选择器应该在Android中关闭而不点击“确定”按钮

    private void updateDOB() {
    String myFormat = "yyyy/MM/dd"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
          btnDOB.setText(sdf.format(calendar.getTime()));
             tvDOB.setTextColor(ContextCompat.getColor(getApplicationContext(),    R.color.colorPrimary));
}

private void selectDOB() {
    DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, day);
            updateDOB();
        }
    };
    new DatePickerDialog(ActivityAddChild.this, listener,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)).show();
} 

2 个答案:

答案 0 :(得分:2)

@Override onDateChangeddismiss();

new DatePickerDialog(context, null, year, month, day) {
    @Override
    public void onDateChanged(@NonNull DatePicker view, int year, int month, int dayOfMonth) {
        /* Here you got the date without "OnDateSetListener" */

        dismiss();
    }
}.show();

引自this回答。

请注意,这不适用于Android 5.0 see there

改为使用MaterialDateTimePicker

答案 1 :(得分:0)

class CustomDatePickerDialog(
        context: Context,
        private val calendar: Calendar,
        private val callback: (newTimestamp: Long) -> Unit
) : DatePickerDialog(context, createListener(calendar, callback), calendar[Calendar.YEAR], calendar[Calendar.MONTH], calendar[Calendar.DAY_OF_MONTH]) {

    override fun onDateChanged(view: DatePicker, year: Int, month: Int, dayOfMonth: Int) {
        super.onDateChanged(view, year, month, dayOfMonth)
        dateChangeHandler(year, month, dayOfMonth, calendar, callback)
        dismiss()
    }

    companion object {
        fun dateChangeHandler(year: Int, month: Int, day: Int, calendar: Calendar, callback: (newTimestamp: Long) -> Unit) {
            calendar[year, month, day, 0, 0] = 0
            callback(calendar.timeInMillis)
        }

        fun createListener(calendar: Calendar, callback: (newTimestamp: Long) -> Unit) = OnDateSetListener { _: DatePicker?, i: Int, i1: Int, i2: Int ->
            dateChangeHandler(i, i1, i2, calendar, callback)
        }
    }
}


fun Context.calendarOnClick(currentDate: Long?, callback: (newTimestamp: Long) -> Unit) {
    val calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"))
    currentDate?.let { calendar.timeInMillis = it }
    CustomDatePickerDialog(this, calendar, callback).show()
}