我正在阅读Big Nerd Ranch Android编程手册。我正在处理CriminalIntent项目,我正在尝试设置一个DatePicker和TimePicker来设置犯罪的日期和时间。"我的DatePicker对话框工作正常,当日期更改,一切正常更新,没有问题。
问题来自TimePicker。出于某种原因,onTimeChangedListener似乎没有触发,因此时间没有正确更新。我已经在我的代码中复制了将侦听器设置为TimePicker。我有一个日志声明,当我改变时间时永远不会触发,这就是为什么我认为这就是问题所在。
TimePicker timePicker = (TimePicker) v.findViewById(R.id.dialog_time_picker);
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// Get the date
date = new GregorianCalendar(year, month, day, hourOfDay, minute).getTime();
Log.d("TimePickerFragment", "hour: " + hourOfDay + "; minute: " + minute);
// Save this date
getArguments().putSerializable(EXTRA_TIME, date);
}
});
以下是我设置小时和分钟的代码:
date = (Date) getArguments().getSerializable(EXTRA_TIME);
// Create a calendar to get hour, minute, and AM/PM info
cal = Calendar.getInstance();
cal.setTime(date);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int amPm = cal.get(Calendar.AM_PM); // 0 = AM 1 = PM
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
如果您需要任何其他代码,请告诉我
答案 0 :(得分:5)
在Lollipop(5.0)之前,每当时间发生变化时,TimePicker视图都会触发onTimeChanged事件,允许应用程序 动态响应选择器当前指定的时间。
在Lollipop中,Timepicker随附
机器人:timePickerMode ="时钟"
在时钟模式下,当时间改变时,onTimeChanged事件不会被触发。
所以最佳方式最好用 android:timePickerMode =" spinner"
<TimePicker
android:id="@+id/timepick_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:timePickerMode="spinner"/>
答案 1 :(得分:0)
使用TimePickerDialog
和OnTimeSetListener
;将您的代码放在侦听器的方法onTimeSet
中。当用户选择时间时,将调用此方法。
Calendar mcurrentDate = Calendar.getInstance();
int mHour = mcurrentDate.get(Calendar.HOUR_OF_DAY);
int mMinute = mcurrentDate.get(Calendar.MINUTE);
TimePickerDialog mTimePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
date = new GregorianCalendar(year, month, day, hourOfDay, minute).getTime();
Log.d("TimePickerFragment", "hour: " + hourOfDay + "; minute: " + minute);
getArguments().putSerializable(EXTRA_TIME, date);
}
}, mHour, mMinute, true);
mTimePicker.setTitle("Select Time");
mTimePicker.show();