Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android中DatePicker和TimePicker的使用方法詳解

android中DatePicker和TimePicker的使用方法詳解

編輯:關於Android編程

本文以實例講述了android中DatePicker和TimePicker的使用方法,具體步驟如下:
下面是實現具體功能的代碼,其中main.xml代碼為:

<?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" >

  <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="請選擇購買本書的具體時間" />

  <DatePicker
    android:id="@+id/datePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal" />

  <TimePicker
    android:id="@+id/timePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal" />

  <EditText
    android:id="@+id/show"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:cursorVisible="false"
    android:editable="false" />

</LinearLayout>

java代碼為:

public class AndroidDemo5Activity extends Activity {

 // 記錄當前的時間
 private int year;
 private int month;
 private int day;
 private int hour;
 private int minute;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 DatePicker date = (DatePicker) findViewById(R.id.datePicker);
 TimePicker time = (TimePicker) findViewById(R.id.timePicker);
 // 或許當前的年月日,小時,分鐘
 Calendar ca = Calendar.getInstance();
 year = ca.get(Calendar.YEAR);
 month = ca.get(Calendar.MONTH);
 day = ca.get(Calendar.DAY_OF_MONTH);
 hour = ca.get(Calendar.HOUR);
 minute = ca.get(Calendar.MINUTE);

 // 初始化DatePicker
 date.init(year, month, day, new OnDateChangedListener() {

  @Override
  public void onDateChanged(DatePicker arg0, int year, int month,
   int day) {
  AndroidDemo5Activity.this.year = year;
  AndroidDemo5Activity.this.month = month;
  AndroidDemo5Activity.this.day = day;
  // 顯示當前時間和日期
  showDate(year, month, day, hour, minute);
  }

 });

 // 為TimerPicker指定事件監聽器
 time.setOnTimeChangedListener(new OnTimeChangedListener() {

  @Override
  public void onTimeChanged(TimePicker arg0, int hour, int minute) {
  AndroidDemo5Activity.this.hour = hour;
  AndroidDemo5Activity.this.minute = minute;
  }
 });
 }

 protected void showDate(int year2, int month2, int day2, int hour2,
  int minute2) {
 EditText text = (EditText) findViewById(R.id.show);
 text.setText("您的購買時間為:" + year2 + "年" + month2 + "月" + day2 + "日"
  + hour2 + "時" + minute2 + "分");

 }
}

運行效果如下圖所示:

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved