Android中的自定义时间选择器

时间:2018-01-23 02:44:04

标签: android timepicker

我有代码显示时间选择器对话框,我已经制作了一个过滤器setMinTime和setMaxTime,但我想更详细地过滤。 如何为今天和其他日期时间选择器制作过滤器?

今天过滤:

timepickerdialog.setMinTime(now.get(Calendar.HOUR_OF_DAY), 0, 0);
timepickerdialog.setMaxTime(16, 0, 0);

过滤其他日子:

timepickerdialog.setMinTime(8, 0, 0);
timepickerdialog.setMaxTime(16, 0, 0);

完整代码:

public void timePicker(){
    Calendar now = Calendar.getInstance();
    TimePickerDialog timepickerdialog = TimePickerDialog.newInstance(
            FormTestDrive.this,
            now.get(Calendar.HOUR_OF_DAY),
            now.get(Calendar.MINUTE),
            true);

    timepickerdialog.setMinTime(8, 0, 0);
    timepickerdialog.setMaxTime(16, 0, 0);

    timepickerdialog.setThemeDark(false);
    timepickerdialog.vibrate(false);
    timepickerdialog.dismissOnPause(false);

    timepickerdialog.show(getFragmentManager(), "Timepickerdialog");
}

1 个答案:

答案 0 :(得分:0)

首先,您需要检查DatePicker中的选定日期是否为今天,并将今天的日期布尔标志发送到timePicker方法,如下所示:

new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                Calendar selectedDate =  Calendar.getInstance();
                selectedDate.set(Calendar.YEAR,year);
                selectedDate.set(Calendar.MONTH,monthOfYear);
                selectedDate.set(Calendar.DAY_OF_MONTH,dayOfMonth);

                openTimePicker(DateUtils.isToday(selectedDate.getTimeInMillis()));

            }
        }, Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();

将今天的日期布尔标志参数用于timePicker方法,如下所示设置最小和最大时间如下:

public void timePicker(boolean isTodayDate){
        int minHour = 8;
        int maxHour = 16;
        Calendar now = Calendar.getInstance();
        TimePickerDialog timepickerdialog = TimePickerDialog.newInstance(
                FormTestDrive.this,
                now.get(Calendar.HOUR_OF_DAY),
                now.get(Calendar.MINUTE),
                true);

        if(isTodayDate){
            if(now.get(Calendar.HOUR_OF_DAY)>8 && now.get(Calendar.HOUR_OF_DAY)<16){
                minHour = now.get(Calendar.HOUR_OF_DAY);
            }
        }

        timepickerdialog.setMinTime(minHour, 0, 0);
        timepickerdialog.setMaxTime(maxHour, 0, 0);

        timepickerdialog.setThemeDark(false);
        timepickerdialog.vibrate(false);
        timepickerdialog.dismissOnPause(false);

        timepickerdialog.show(getFragmentManager(), "Timepickerdialog");
    }