在應用程式中新增挑選器

Android 提供控制項,讓使用者選擇可以立即使用的對話方塊,選擇時間或日期。這些挑選器提供用於選取時間部分 (小時、分鐘、上午/下午) 或日期 (月、日、年) 的控制項。

Material.io 的時間挑選器範例
圖 1.在行動版日曆選擇器中選取時段。

使用這些挑選器,有助於確保使用者能選擇有效、格式正確且符合使用者當地區域的時間或日期。

Material.io 中的強制回應日期挑選器範例
圖 2. 強制回應日期挑選器。

建議您使用 DialogFragment 代管每個時間或日期挑選器。DialogFragment 可為您管理對話方塊的生命週期,並允許在不同版面配置設定中顯示挑選器,例如在手機的基本對話方塊中顯示,或做為大型螢幕上版面配置的內嵌部分顯示。

建立時間挑選器

如要使用 DialogFragment 顯示 TimePickerDialog,請定義擴充 DialogFragment 的片段類別,並從片段的 onCreateDialog() 方法傳回 TimePickerDialog

擴充時間挑選器的 DialogFragment

如要為 TimePickerDialog 定義 DialogFragment,請按照下列步驟操作:

  • 定義 onCreateDialog() 方法以傳回 TimePickerDialog 的例項。
  • 實作 TimePickerDialog.OnTimeSetListener 介面,以便在使用者設定時間時接收回呼。

範例如下:

Kotlin

class TimePickerFragment : DialogFragment(), TimePickerDialog.OnTimeSetListener {

    override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
        // Use the current time as the default values for the picker.
        val c = Calendar.getInstance()
        val hour = c.get(Calendar.HOUR_OF_DAY)
        val minute = c.get(Calendar.MINUTE)

        // Create a new instance of TimePickerDialog and return it.
        return TimePickerDialog(activity, this, hour, minute, DateFormat.is24HourFormat(activity))
    }

    override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
        // Do something with the time the user picks.
    }
}

Java

public static class TimePickerFragment extends DialogFragment
                            implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker.
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it.
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time the user picks.
    }
}

如要瞭解建構函式引數,請參閱 TimePickerDialog 類別。

現在,您只需要將這個片段的執行個體新增至活動即可。

顯示時間挑選器

按照上述範例定義 DialogFragment 後,您可以建立 DialogFragment 的執行個體並呼叫 show() 方法,以顯示時間挑選器。

例如,在輕觸下方按鈕後,即會呼叫一個方法來顯示對話方塊:

<Button
    android:id="@+id/pickTime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Pick time" />

當使用者輕觸此按鈕時,系統會呼叫以下方法:

Kotlin

findViewById<Button>(R.id.pickTime).setOnClickListener {
    TimePickerFragment().show(supportFragmentManager, "timePicker")
}

Java

findViewById<Button>(R.id.pickTime).setOnClickListener {
    TimePickerFragment().show(supportFragmentManager, "timePicker");
}

這個方法會在上述範例中定義的新 DialogFragment 例項上呼叫 show()show() 方法需要 FragmentManager 的執行個體和片段的專屬標記名稱。

建立日期挑選器

建立 DatePickerDialog 與建立 TimePickerDialog 類似。差別在於您為片段建立的對話方塊。

如要使用 DialogFragment 顯示 DatePickerDialog,請定義擴充 DialogFragment 的片段類別,並從片段的 onCreateDialog() 方法傳回 DatePickerDialog

擴充日期挑選器的 DialogFragment

如要為 DatePickerDialog 定義 DialogFragment,請按照下列步驟操作:

  • 定義 onCreateDialog() 方法以傳回 DatePickerDialog 的例項。
  • 實作 DatePickerDialog.OnDateSetListener 介面,以便在使用者設定日期時接收回呼。

範例如下:

Kotlin

class DatePickerFragment : DialogFragment(), DatePickerDialog.OnDateSetListener {

    override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
        // Use the current date as the default date in the picker.
        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)
        val day = c.get(Calendar.DAY_OF_MONTH)

        // Create a new instance of DatePickerDialog and return it.
        return DatePickerDialog(requireContext(), this, year, month, day)

    }

    override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        // Do something with the date the user picks.
    }
}

Java

public static class DatePickerFragment extends DialogFragment
                            implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker.
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it.
        return new DatePickerDialog(requireContext(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date the user picks.
    }
}

如要瞭解建構函式引數,請參閱 DatePickerDialog 類別。

您只需要一個事件就能將這個片段的執行個體新增至活動。

顯示日期挑選器

按照上述範例定義 DialogFragment 後,您可以建立 DialogFragment 的執行個體並呼叫 show(),以顯示日期挑選器。

例如,在輕觸下方按鈕後,即會呼叫一個方法來顯示對話方塊:

<Button
    android:id="@+id/pickDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Pick date"/>

當使用者輕觸此按鈕時,系統會呼叫以下方法:

Kotlin

findViewById<Button>(R.id.pickDate).setOnClickListener {
    val newFragment = DatePickerFragment()
    newFragment.show(supportFragmentManager, "datePicker")
}

Java

findViewById<Button>(R.id.pickDate).setOnClickListener {
    val newFragment = DatePickerFragment();
    newFragment.show(supportFragmentManager, "datePicker");
}

這個方法會在上述範例中定義的新 DialogFragment 例項上呼叫 show()show() 方法需要 FragmentManager 的執行個體和片段的專屬標記名稱。

透過自動填入功能使用挑選器

Android 在 2017 年推出了自動填入架構,可讓使用者儲存用於在不同應用程式中填寫表單的資料。挑選器提供了一個 UI,可讓使用者變更日期或時間資料儲存欄位中的值,因此在自動填入情境中可能會非常有用。例如在信用卡表單中,日期挑選器可讓使用者輸入或變更信用卡的到期日。

由於挑選器是對話方塊,因此它們不會與其他欄位一起顯示在活動中。如要在未顯示挑選器時顯示挑選器資料,可以使用另一檢視區塊 (例如 EditText),在未顯示挑選器時顯示該值。

EditText 物件本身預期的自動填入資料類型為 AUTOFILL_TYPE_TEXT。相較之下,自動填入服務會將資料儲存為 AUTOFILL_TYPE_DATE,以建立適當的表示法。如要解決類型不一致的問題,建議您建立繼承自 EditText 的自訂檢視畫面,並實作正確處理 AUTOFILL_TYPE_DATE 類型值所需的方法。

請按照下列步驟建立 EditText 的子類別,以便處理 AUTOFILL_TYPE_DATE 類型的值:

  1. 建立從 EditText 沿用的類別。
  2. 實作 getAutofillType() 方法,這個方法會傳回 AUTOFILL_TYPE_DATE
  3. 實作 getAutofillValue() 方法,傳回表示日期 (以毫秒為單位) 的 AutofillValue 物件。如要建立傳回物件,請使用 forDate() 方法產生 AutofillValue 物件。
  4. 實作 autofill() 方法。這個方法會提供處理 AutofillValue 參數的邏輯,參數類型為 AUTOFILL_TYPE_DATE。如要處理參數,請為參數建立適當的字串表示法,例如 mm/yyyy。使用字串表示法設定檢視區塊的 text 屬性。
  5. 實作以下功能:當使用者想要在 EditText 的自訂子類別中編輯日期時,顯示挑選器。檢視區塊會更新 text 屬性,並以字串表示使用者在挑選器上選取的值。

如要查看處理 AUTOFILL_TYPE_DATE 值的 EditText 子類別範例,請參閱 JavaKotlin 中的自動填入架構範例。

如要進一步瞭解如何為自訂檢視畫面提供自動填入支援,請參閱「自動填入架構」。