我想通过timePickerDialog获取AM / PM值。我的代码是这样的,它通过timepickerdialog通过用户输入并设置警报。我在这里收到用户输入
datetime = Calendar.getInstance();
new TimePickerDialog(this,this,datetime.get(Calendar.HOUR),datetime.get(Calendar.MINUTE),false).show();
现在当onTimeSet函数调用i时,可以获得用户选择的小时和分钟,但无法获得用户选择的AM / PM值。这是其他代码
public void onTimeSet(TimePicker view, int hourOfDay, int minute) { try { Calendar time = Calendar.getInstance();
String am_pm;
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
time.set(Calendar.HOUR, hourOfDay);
time.set(Calendar.MINUTE, minute);
//time.set(Calendar.SECOND, 0);
//time.set(Calendar.MILLISECOND, 0);
//time.set(Calendar.AM_PM,datetime.PM);
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmMgr.set(AlarmManager.RTC_WAKEUP,time.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_long);
答案 0 :(得分:7)
在侦听器中创建新的日历实例,如下所示
Calendar datetime = Calendar.getInstance();
c.set(Calendar.HOUR, mHour);
c.set(Calendar.MINUTE, mMinute);
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime.get(Calendar.AM_PM) == Calendar.PM) {
am_pm = "PM";
if (hourOfDay > 12)
hourOfDay = hourOfDay - 12;
}
已更新:
Calendar mCalendar = Calendar.getInstance();
mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
mMinute = mCalendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(mActivity, mTimeSetListener, mHour, mMinute, false);
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
mCalendar.set(Calendar.MINUTE, mMinute);
SimpleDateFormat mSDF = new SimpleDateFormat("hh:mm a");
String time = mSDF.format(mCalendar.getTime());
}
}
答案 1 :(得分:2)
也许这可以回答你的问题。
答案 2 :(得分:0)
试试这个:
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String am_pm = "";
Calendar datetime = Calendar.getInstance();
datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
datetime.set(Calendar.MINUTE, minute);
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
String strHrsToShow = (datetime.get(Calendar.HOUR) == 0) ?"12":datetime.get(Calendar.HOUR)+"";
((Button)getActivity().findViewById(R.id.btnEventStartTime)).setText( strHrsToShow+":"+datetime.get(Calendar.MINUTE)+" "+am_pm );
}