1.DatePicker和TimePicker
XML中的DatePicker和TimePicker控件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/dateDefault" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/timeDefault" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>分别使用日期和时间初始化DatePicker和TimePicker
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.datetimepicker); TextView dateDefault = (TextView)findViewById(R.id.dateDefault); TextView timeDefault = (TextView)findViewById(R.id.timeDefault); DatePicker dp = (DatePicker)this.findViewById(R.id.datePicker); // The month, and just the month, is zero-based. Add 1 for display. dateDefault.setText("Date defaulted to " + (dp.getMonth() + 1) + "/" + dp.getDayOfMonth() + "/" + dp.getYear()); // And here, subtract 1 from December (12) to set it to December dp.init(2008, 11, 10, null); TimePicker tp = (TimePicker)this.findViewById(R.id.timePicker); java.util.Formatter timeF = new java.util.Formatter(); timeF.format("Time defaulted to %d:%02d", tp.getCurrentHour(), tp.getCurrentMinute()); timeDefault.setText(timeF.toString()); tp.setIs24HourView(true); tp.setCurrentHour(new Integer(10)); tp.setCurrentMinute(new Integer(10)); }效果图:
2.AnalogClock和DigitalClock
在XML中添加DigitalColck和AnalogClock
<DigitalClock android:layout_width="wrap_content" android:layout_height="wrap_content" /> <AnalogClock android:layout_width="fill_parent" android:layout_height="wrap_content" />
这两个控件只能显示当前时间,它们不支持修改日期或时间。换句话说,它们只是始终,唯一的功能就是显示当前的时间。但是,这两个时钟的一个不错的地方是它们可以自行更新,无需执行任何操作。
效果图: