使用TimePicker,可以讓使用者去選擇一天中的事件,包括24小時制和AM/PM制。下面的例子將會展示如何使用TimePicker。
1、建立一個工程:BasicViews4。
2、main.xml中的代碼。
[html]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/btnSet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am all set!"
android:onClick="onClick" />
<TimePicker android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
3、BasicViews4Activity.java中的代碼。
[java]
package net.learn2develop.BasicViews4;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;
public class BasicViews4Activity extends Activity {
TimePicker timePicker;
int hour, minute;
int yr, month, day;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timePicker = (TimePicker) findViewById(R.id.timePicker);
// 通過調用setIs24HourView()方法,可以設定TimePicker的格式。
timePicker.setIs24HourView(true);
}
public void onClick(View view) {
Toast.makeText(getBaseContext(),
"Date selected:" + (datePicker.getMonth() + 1) +
"/" + datePicker.getDayOfMonth() +
"/" + datePicker.getYear() + "\n" +
"Time selected:" + timePicker.getCurrentHour() +
":" + timePicker.getCurrentMinute(),
Toast.LENGTH_SHORT).show();
}
}
4、F11調試。