您好,我正在尝试计算用户 7.5 的睡眠时间。应用程序应该建议用户应该在准确的时间上床睡觉。例如,她选择早上 7:00 作为她的起床时间,该应用程序会建议她在上午 11:30 之前睡觉 我目前尝试的是这样的:
public class TimepickerActivity extends Activity implements TimePickerDialog.OnTimeSetListener {
Button btn1, btn2;
TimePicker picker;
TextView tv;
private int hour;
private int minute;
static final int TIME_DIALOG_ID = 999;
@Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_timepicker );
btn1 = (Button) findViewById (R.id.btnShow);
btn2 = (Button) findViewById (R.id.btnSleepingTime);
tv = (TextView) findViewById (R.id.textView1);
picker = (TimePicker) findViewById (R.id.timePicker1);
setCurrentTimeOnView();
addListenerOnButton();
}
// display current time
public void setCurrentTimeOnView() {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
tv.setText( new StringBuilder().append(pad(hour))
.append(":").append(pad(minute)));
// set current time into timepicker
picker.setCurrentHour(hour);
picker.setCurrentMinute(minute);
}
public void addListenerOnButton() {
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR, - selectedHour);
c.add(Calendar.MINUTE, - selectedMinute);
// set current time into timepicker
picker.setCurrentHour(hour + 7);
picker.setCurrentMinute(minute + 30);
// set current time into textview
//tv.setText(new StringBuilder().append(pad(hour))
// .append(":").append(pad(minute)));
tv.setText( picker.getCurrentHour().toString() + ":" + picker.getCurrentMinute().toString() );
}
};
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
}
}
当我输入早上 7:00 作为我的起床时间时,结果是下午 2:30。但应该是下午 12 点 30 分。感谢任何帮助。