不允许时间选择器选择过去的时间值

时间:2013-11-18 05:48:35

标签: android datetime android-timepicker

我正在我的项目中实现时间选择器对话框。它不应该选择与当前时间相关的过去值。我的意思是设定采摘的最短和最长时间。

以下是我所做的时间戳的过程:

 // Current Hour
 hour = cal.get(Calendar.HOUR_OF_DAY);

 // Current Minute
 minute = cal.get(Calendar.MINUTE);

 return new TimePickerDialog(this, timePickerListener, hour, minute, false);

我已完成以下过程到日期选择器对话框。它有效,但对于时间选择器,我找不到任何过程。

日期选择器:

Calendar calendar = Calendar.getInstance();

dialog = new DatePickerDialog(this, onDateSet, cYear, cMonth, cDay);
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());

所以请帮助如何在时间选择器对话框中实现这一点。

1 个答案:

答案 0 :(得分:2)

您可以将此作为起点。

扩展TimePickerDialog并添加了2个方法setMin和setMax。

在onTimeChanged方法中检查新时间相对于最小/最大时间是否有效。

它仍然需要一些抛光......

public class BoundTimePickerDialog extends TimePickerDialog {

    private int minHour = -1, minMinute = -1, maxHour = 100, maxMinute = 100;

    private int currentHour, currentMinute;

    public BoundTimePickerDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
        super(context, callBack, hourOfDay, minute, is24HourView);
    }

    public void setMin(int hour, int minute) {
        minHour = hour;
        minMinute = minute;
    }

    public void setMax(int hour, int minute) {
        maxHour = hour;
        maxMinute = minute;
    }

    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        super.onTimeChanged(view, hourOfDay, minute);

        boolean validTime;
        if(hourOfDay < minHour) {
            validTime = false;
        }
        else if(hourOfDay == minHour) {
            validTime = minute >= minMinute;
        }
        else if(hourOfDay == maxHour) {
            validTime = minute <= maxMinute;
        }
        else {
            validTime = true;
        }

        if(validTime) {
            currentHour = hourOfDay;
            currentMinute = minute;
        }
        else {
            updateTime(currentHour, currentMinute);
        }
    }
}