Android docs中的范例,简单翻译整理如下。
--------------------------------------------
1、创建新项目,名称HelloTimePicker;
2、修改res/layout/main.xml,内容如下:
3、修改HelloTimePicker.java,增加成员变量定义,代码如下:
4、修改HelloTimePicker.java的onCreate方法,内容如下:
5、修改HelloTimePicker.java增加updateDisplay和pad方法,内容如下:
6、修改HelloTimePicker.java增加时间选择对话框,内容如下:
7、修改HelloTimePicker.java增加onCreateDialog方法,内容如下:
8、运行项目,即可看到运行效果,如下图所示:
[img]http://dl.iteye.com/upload/attachment/424630/5fb4908d-15d0-39cd-8ffe-c72264efacfc.png[/img]
--------------------------------------------
1、创建新项目,名称HelloTimePicker;
2、修改res/layout/main.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/timeDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
<Button android:id="@+id/pickTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change the time"/>
</LinearLayout>
3、修改HelloTimePicker.java,增加成员变量定义,代码如下:
private TextView mTimeDisplay;
private Button mPickTime;
private int mHour;
private int mMinute;
static final int TIME_DIALOG_ID = 0;
4、修改HelloTimePicker.java的onCreate方法,内容如下:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// capture our View elements
mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
mPickTime = (Button) findViewById(R.id.pickTime);
// add a click listener to the button
mPickTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
// get the current time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// display the current date
updateDisplay();
}
5、修改HelloTimePicker.java增加updateDisplay和pad方法,内容如下:
// updates the time we display in the TextView
private void updateDisplay() {
mTimeDisplay.setText(
new StringBuilder()
.append(pad(mHour)).append(":")
.append(pad(mMinute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
6、修改HelloTimePicker.java增加时间选择对话框,内容如下:
// the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
updateDisplay();
}
};
7、修改HelloTimePicker.java增加onCreateDialog方法,内容如下:
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
}
return null;
}
8、运行项目,即可看到运行效果,如下图所示:
[img]http://dl.iteye.com/upload/attachment/424630/5fb4908d-15d0-39cd-8ffe-c72264efacfc.png[/img]