timepicker也繼承自framelayout類。時間選擇控制項向使用者顯示一天中的時間(可以為24小時,也可以為am/pm制),並允許使用者進行選擇。如果要捕獲使用者修改時間資料的事件,便需要為timepicker添加ontimechangedlistener監聽器
以下類比日期與時間選擇控制項的用法
目錄結構
main.xml布局檔案
<?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">
<datepicker android:id="@+id/datepicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
<edittext android:id="@+id/dateet"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorvisible="false"
android:editable="false"/>
<timepicker android:id="@+id/timepicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
<edittext android:id="@+id/timeet"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorvisible="false"
android:editable="false"/>
</linearlayout>
dptpactivity類
package com.ljq.activity;
import java.util.calendar;
import android.app.activity;
import android.os.bundle;
import android.widget.datepicker;
import android.widget.edittext;
import android.widget.timepicker;
import android.widget.datepicker.ondatechangedlistener;
import android.widget.timepicker.ontimechangedlistener;
public class dptpactivity extends activity {
private edittext dateet=null;
private edittext timeet=null;
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
dateet=(edittext)findviewbyid(r.id.dateet);
timeet=(edittext)findviewbyid(r.id.timeet);
datepicker datepicker=(datepicker)findviewbyid(r.id.datepicker);
timepicker timepicker=(timepicker)findviewbyid(r.id.timepicker);
calendar calendar=calendar.getinstance();
int year=calendar.get(calendar.year);
int monthofyear=calendar.get(calendar.month);
int dayofmonth=calendar.get(calendar.day_of_month);
datepicker.init(year, monthofyear, dayofmonth, new ondatechangedlistener(){
public void ondatechanged(datepicker view, int year,
int monthofyear, int dayofmonth) {
dateet.settext("您選擇的日期是:"+year+"年"+(monthofyear+1)+"月"+dayofmonth+"日。");
}
});
timepicker.setontimechangedlistener(new ontimechangedlistener(){
public void ontimechanged(timepicker view, int hourofday, int minute) {
timeet.settext("您選擇的時間是:"+hourofday+"時"+minute+"分。");
}
});
}
}
運行結果