Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android DatePicker 日期選擇器用法完整示範

編輯:關於 Android 程式設計

讓使用者挑一個日期,是表單類 App 再常見不過的需求。Android 內建的 DatePickerDialog 就能勝任,幾行程式碼搞定,而且原生體驗與系統風格一致。本文用一個最小可運行的例子把用法講清楚。

版面配置

一個顯示文字的 TextView,加上一顆觸發挑選的按鈕,結構非常樸素:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/textViewDateDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btnPickDate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change the date" /> </LinearLayout>

Activity 程式碼

 package com.example.mars_2200_datepicker; import java.util.Calendar; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.app.DatePickerDialog; import android.app.Dialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import android.os.Build; public class MainActivity extends ActionBarActivity { private TextView textViewDateDisplay; private Button btnPickDate; private int mYear; private int mMonth; private int mDay; static final int DATE_DIALOG_ID = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewDateDisplay = (TextView) findViewById(R.id.textViewDateDisplay); btnPickDate = (Button) findViewById(R.id.btnPickDate); btnPickDate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DATE_DIALOG_ID); } }); final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); updateDisplay(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } private void updateDisplay() { textViewDateDisplay.setText(new StringBuilder().append(mYear).append("-") .append(mMonth + 1).append("-").append(mDay).append(" ")); } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDisplay(); } }; protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null; } }

幾個值得留意的細節

月份要加一。這是新手最常踩的坑:Calendar.MONTH 的取值從 0 開始,一月是 0、十二月是 11。所以顯示時必須 mMonth + 1,而在回傳給 DatePickerDialog 時又要還原成 0 起始的值,兩邊不要搞混。

初始值取自系統時間。用 Calendar.getInstance() 抓今天,讓對話方塊預設停在當前日期,符合多數使用者的期待。

對話方塊用 onCreateDialog 管理。透過 showDialog(id) 觸發,Activity 會自行快取與重建,即使螢幕旋轉也能保住狀態,比自己 new 一個要穩妥。

如果專案 targetSdk 較新,也可以改用 DatePickerDialog 的直接建構方式或 DialogFragment 寫法,但上面這套邏輯骨架是不變的。

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