Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

第32章 Android 日期與時間對話框:DatePickerDialog 與 TimePickerDialog 實作

編輯:Android 技術基礎

要讓使用者挑一個日期或時刻,最糟的做法是丟一個空白輸入框讓他手打「2026-08-26」。Android 內建的日期與時間對話框,會自動依系統地區給出對應的日曆與時鐘介面,是既省事又不容易出錯的選擇。

一、版面設計

開啟 res/layout/activity_main.xml。這裡有一個小技巧:把顯示用的 EditText 設為不可編輯、隱藏游標,讓它只當「結果顯示區」,避免使用者繞過對話框直接打字。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

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

    <Button
        android:id="@+id/dateBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="日期對話框" />

    <Button
        android:id="@+id/timeBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="時間對話框" />

    <DigitalClock
        android:id="@+id/DigitalClock01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20dip" />

    <AnalogClock
        android:id="@+id/analogClock"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
</LinearLayout>

版面下方還放了 DigitalClock 與 AnalogClock 兩個時鐘元件,方便你比對「挑選的時間」和「目前的時間」。

二、程式:用 showDialog + onCreateDialog 管理

開啟 src/com.genwoxue.datetimedialog/MainActivity.java:

package com.genwoxue.datetimedialog;

import java.util.Calendar;

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.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class MainActivity extends Activity {

    private Button dateBtn = null;
    private Button timeBtn = null;
    private EditText et = null;

    private static final int DATE_DIALOG = 0;
    private static final int TIME_DIALOG = 1;

    private Calendar c = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et      = (EditText) findViewById(R.id.et);
        dateBtn = (Button) findViewById(R.id.dateBtn);
        timeBtn = (Button) findViewById(R.id.timeBtn);

        dateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(DATE_DIALOG);
            }
        });

        timeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(TIME_DIALOG);
            }
        });
    }

    /** 建立日期與時間選擇對話框 */
    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        switch (id) {
            case DATE_DIALOG:
                c = Calendar.getInstance();
                dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
                        // 注意:month 從 0 開始,顯示時要 +1
                        et.setText("您選擇了:" + year + "年" + (month + 1) + "月" + dayOfMonth + "日");
                    }
                },
                c.get(Calendar.YEAR),
                c.get(Calendar.MONTH),
                c.get(Calendar.DAY_OF_MONTH));
                break;

            case TIME_DIALOG:
                c = Calendar.getInstance();
                dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        et.setText("您選擇了:" + hourOfDay + "時" + minute + "分");
                    }
                },
                c.get(Calendar.HOUR_OF_DAY),
                c.get(Calendar.MINUTE),
                false);   // false = 12 小時制;true = 24 小時制
                break;
        }
        return dialog;
    }
}

三、兩個一定要記住的細節

月份從 0 開始算。 Calendar.MONTH 的回傳值 0 代表一月,所以顯示給使用者看之前必須 +1,這是新手最常出現「日期少一個月」的原因。

最後一個參數決定時制。 TimePickerDialog 的最後一個 boolean 傳 false 走 12 小時制、true 走 24 小時制。專案若有固定格式需求,明確指定比依賴系統設定更可靠。

另外,showDialog() 搭配 onCreateDialog() 是舊寫法:系統會幫你快取對話框、並在 Activity 重建時自動還原狀態。新專案更常直接 new DatePickerDialog(...).show(),程式碼更直觀,但旋轉螢幕後的狀態就得自己處理。

四、執行結果

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved