TimePicker在TimePicker中显示当前时间作为默认时间,但是如果我想根据我的要求在时间选择器中设置默认时间呢?
当我写这篇文章的时候,它是11:10,但是在TimePicker中,我喜欢显示01:00作为默认值(我的平均2小时差,分钟应该只有00)
static final int TIME_DIALOG_ID = 1;
public int year,month,day,hour,minute;
private int mYear, mMonth, mDay,mHour,mMinute;
public TimePickerActivity() {
// Assign current Date and Time Values to Variables
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
}
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int min) {
hour = hourOfDay;
minute = min;
String formattedMinutes = "" + min;
String formattedHour = "" + hourOfDay;
if (hourOfDay < 10) {
formattedHour = "0" + hourOfDay;
}
if (min < 10) {
formattedMinutes = "0" + min;
}
textTime.setText(formattedHour + ":" + formattedMinutes);
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
TimePickerDialog timePickerDialog = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
return timePickerDialog;
}
return null;
}
您可以使用以下代码:
private TimePicker timePicker;
timePicker = (TimePicker) dialog.findViewById(R.id.timePickerDialog);
if(DateFormat.is24HourFormat(getActivity()){
timePicker.setIs24HourView(true);
}else {
timePicker.setIs24HourView(false);
}
// here you can define your hour and minute value.
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
你可以试试下面的代码
SimpleDateFormat sdf = new SimpleDateFormat("hh:ss");
Date date = null;
try {
date = sdf.parse("07:00");
} catch (ParseException e) {
}
Calendar c = Calendar.getInstance();
c.setTime(date);
TimePicker picker = new TimePicker(getApplicationContext());
picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
picker.setCurrentMinute(c.get(Calendar.MINUTE));