2013-12-18 74 views
0

我有一个24小时格式的时间选择器。现在我想以24小时格式显示当前设备时间,无论设备时间格式如何。现在我的设备是12小时格式,所以例如我的时间是下午2点04分,时间选择器应该是14点04分。基于设备时间在timepicker中设置默认时间

这是我的代码或timepicker。它在不同的布局上,因为我在对话框中显示它们。

XML:

<LinearLayout android:id="@+id/datetimepickerLayout" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" xmlns:android="http://schemas.android.com/apk/res/android"> 
<DatePicker android:id="@+id/datePicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"></DatePicker> 
<TimePicker android:id="@+id/timePicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"></TimePicker> 

<Button 
android:id="@+id/setdatetimeBtn1" 
android:text="Set" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_marginTop="10dp" 
android:layout_gravity="center"/> 

现在在我的Java代码:

timePicker1 = (TimePicker)dialog.findViewById(R.id.timePicker1); 
datePicker1 = (DatePicker)dialog.findViewById(R.id.datePicker1); 
setDateTimeBtn1 = (Button)dialog.findViewById(R.id.setdatetimeBtn1); 
datePicker1.setCalendarViewShown(false); 
timePicker1.setIs24HourView(true); 

任何想法?谢谢!

+1

看到http://stackoverflow.com/questions/12494074/android-setting-time-in-time-picker-with-the-time-shown-in-text-view –

+0

看到这个链接http:// www .mkyong.com/android/android-date-picker-example/ –

+0

伟大的链接@Shayanpourvatan。谢谢! – ljpv14

回答

1

AFAIK默认情况下,它会使用设备当前的时间,你可以使用下面的代码设置。

Calendar c = Calendar.getInstance(); 
timePicker1.setCurrentHour(c.get(Calendar.HOUR)); 
timePicker1.setCurrentMinute(c.get(Calendar.MINUTE)); 
+0

这正是我需要的。谢谢! – ljpv14

+0

永远欢迎亲爱的!如果它帮助你,然后PLZ接受upvote。 –

+0

对不起。我刚才试图接受,但仍需要等待3分钟。完全忘了它。谢谢! – ljpv14

0

可以使用日历例如象下面这样获取设备时间:

Calendar c = Calendar.getInstance(); 

String CTime =c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND); 
0

试一试。

timePicker1 = (TimePicker)dialog.findViewById(R.id.timePicker1); 
datePicker1 = (DatePicker)dialog.findViewById(R.id.datePicker1); 
setDateTimeBtn1 = (Button)dialog.findViewById(R.id.setdatetimeBtn1); 
    setDateTimeBtn1 .setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      String strDateTime = datePicker1 .getYear() + "-" + (datePicker1 .getMonth() + 1) + "-" + datePicker1 .getDayOfMonth() + " " 
     + timePicker1 .getCurrentHour() + ":" + timePicker1.getCurrentMinute(); 

      Toast.makeText(TimeDate.this, "User selected " + strDateTime + "Time", Toast.LENGTH_LONG).show(); //Generate a toast only if you want 
      finish(); // If you want to continue on that TimeDateActivity 
      // If you want to go to new activity that code you can also write here 
     }}); 
0

@Everyone谁tryed解决上面提到的,他们没有工作,你必须使用你

Calender.HOUR_OF_DAY 

Calender.HOUR 

,而不是我在谷歌搜索整天,直到今天我得到这个上班。

相关问题