7.1.3 TimePicker结合案例详解

TimePicker是Android的时间设置控件。TimePicker类的继承图如下:
java.lang.Object
   ↳android.view.View
     ↳android.view.ViewGroup
       ↳android.widget.FrameLayout
         ↳android.widget.TimePicker
android.widget.TimePicker继承了android.widget.FrameLayout框架布局类。TimePicker例子如图7-8所示,从左到右是小时、分钟、上午和下午设置按钮,改变小时、分钟、上午和下午都会触发OnTimeChanged事件。
 


图7-8 TimePicker
请参考代码清单7-8,完整代码请参考chapter7_1工程中chapter7_TimePicker代码部分。
【代码清单7-8】
public class chapter7_TimePicker extends Activity {
private TextView mTimeDisplay;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timepicker_layout);

TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker);

timePicker.setCurrentHour(12);
timePicker.setCurrentMinute(15);

mTimeDisplay = (TextView) findViewById(R.id.timetextview);

timePicker
.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay,
int minute) {
mTimeDisplay.setText(String.valueOf(hourOfDay) + " : "
+ String.valueOf(minute));
}
});
}
}
timePicker.setCurrentHour()方法设置当前时间,timePicker.setCurrentMinute()方法设置当前分钟。TimePicker.OnTimeChangedListener()是实现时间改变监听接口。
TimePicker的布局文件请参考代码清单7-9,完整代码请参考chapter7_1工程中timepicker_layout.xml代码部分(chapter7_1/res/layout/timepicker_layout.xml)。
【代码清单7-9】
<?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:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<TimePicker android:id="@+id/timePicker"
android:layout_width="wrap_content" android:layout_height="wrap_content">
</TimePicker>

<TextView android:id="@+id/timetextview" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
</LinearLayout>
                                                出自《Android开发案例驱动教程》第七章
posted @ 2011-07-25 17:06  516inc  阅读(233)  评论(0编辑  收藏  举报