我有一个TimePickerDialog的自定义实现,在其中我覆盖onTimeChanged方法做我选择的一些争论。我看到一些帖子要求使用反射来获取此对话框的TimePicker并将onTimeChange listner设置为"这个",为什么我们甚至需要这样做...我的意思是实际的时间选择器代码本身设置timeChangeListner到"这"
我们不应该只是覆盖onTimeChanged方法吗?但事实是,即使onTimeChanged被调用,它被多次调用,而updateTime似乎也没有在timepicker上产生任何影响。 以下是TimePickerDialog的实现:
public class RangeTimePickerDialog extends TimePickerDialog{
private Integer minHour, minMinute, maxHour, maxMinute;
public RangeTimePickerDialog(Context context, OnTimeSetListener listener, int hourOfDay, int minute, boolean is24HourView) {
super(context, listener, hourOfDay, minute, is24HourView);
try {
Class<?> superclass = getClass().getSuperclass();
Field mTimePickerField = superclass.getDeclaredField("mTimePicker");
mTimePickerField.setAccessible(true);
TimePicker mTimePicker = (TimePicker) mTimePickerField.get(this);
mTimePicker.setOnTimeChangedListener(this);
} catch (NoSuchFieldException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
}
}
public void setMinTime(int hour, int minute) {
minHour = hour;
minMinute = minute;
}
public void setMaxTime(int hour, int min) {
maxHour = hour;
maxMinute = min;
}
private void updateDisplay() {
setTitle("Please Select A Valid Time");
}
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Log.d("RangeTimePicker", "onTimeChanged Called");
if (minHour != null) {
if (hourOfDay < minHour || (hourOfDay == minHour && minute <= minMinute)) {
updateTime(minHour, minMinute);
updateDisplay();
}
}
if( maxHour != null) {
if(hourOfDay > maxHour || (hourOfDay ==maxHour && minute > maxMinute)){
updateTime(maxHour, maxMinute);
updateDisplay();
}
}
}
}