Android:使用文本视图中显示的时间在时间选择器中设置时间 [英] Android: Setting time in time picker with the time shown in text view
本文介绍了Android:使用文本视图中显示的时间在时间选择器中设置时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用中,我在文本视图中将时间显示为 07:00 PM.单击文本视图时,会弹出一个时间选择器对话框,在该时间选择器中,我必须显示与文本视图中显示的时间完全相同的时间.但是,我不知道该怎么做.
In my app, I am showing time in text view as 07:00 PM. On click of the text view, a time picker dialog pops up, In that time picker, I have to show exactly the same time as what is appearing in textview. But, I am not getting how to do that.
代码
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm a");
//int hr = 0;
Date date = null;
try
{
date = sdf.parse(resDateArray[3]);
}
catch (ParseException e) {
e.printStackTrace();
}
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
//tp is reference variable for time picker
tp.setCurrentHour(calendar.get(Calendar.HOUR));
tp.setCurrentMinute(calendar.get(Calendar.MINUTE));
}//else
推荐答案
你应该使用 SimpleDateFormat
从你的 String
获取一个 Date
对象>.然后只需调用
You should use a SimpleDateFormat
to get a Date
object from your String
.
Then just call
picker.setCurrentHour(date.getHours())
和
picker.setCurrentMinute(date.getMinutes())
由于 Date
对象已被弃用,您应该使用 Calendar
代替它.您可以通过以下方式实例化 Calendar
:
Since the Date
object is deprecated, you should use a Calendar
instead of it.
You can instantiate a Calendar
this way:
Calendar c = Calendar.getInstance();
c.setTime(date);
picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
picker.setCurrentMinute(c.get(Calendat.MINUTE));
完整代码:
import java.util.Date;
import java.text.SimpleDateFormat; //Don't use "android.icu.text.SimpleDateFormat"
import java.text.ParseException; //Don't use "android.net.ParseException"
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
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));
这篇关于Android:使用文本视图中显示的时间在时间选择器中设置时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文