在應用程式中新增圓形按鈕

試試 Compose 的方式
Jetpack Compose 是 Android 推薦的 UI 工具包。瞭解如何在 Compose 中新增元件。

圓形按鈕可讓使用者從一組互斥的選項中選取一個選項。如果使用者需要查看所有可用的選項,請使用圓形按鈕。如果不需要顯示所有選項,請改用旋轉圖示

來自 material.io 的圓形按鈕範例
圖 1. Material Design 中的圓形按鈕範例。

如要建立每個圓形按鈕選項,請在版面配置中建立 RadioButton。由於圓形按鈕彼此互斥,因此請在 RadioGroup 內將這些按鈕設成一個群組。系統會確保一次只能選取群組中的一個圓形按鈕。

回應點擊事件

當使用者選取圓形按鈕時,對應的 RadioButton 物件會收到點擊事件。

以下範例顯示使用者輕觸群組中 RadioButton 物件的反應:

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton android:id="@+id/radio_pirates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pirates"/>
    <RadioButton android:id="@+id/radio_ninjas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ninjas"/>
</RadioGroup>

在代管此版面配置的 ActivityFragment 中,找出圓形按鈕,並為每個按鈕設定變更事件監聽器,如下所示:

Kotlin

findViewById<RadioButton>(R.id.radio_pirates).setOnCheckedChangeListener { buttonView, isChecked ->
    Log.d("RADIO", "Pirates is checked: $isChecked")
}

findViewById<RadioButton>(R.id.radio_ninjas).setOnCheckedChangeListener { buttonView, isChecked ->
    Log.d("RADIO", "Ninjas is checked: $isChecked")
}

Java

findViewById<RadioButton>(R.id.radio_pirates).setOnCheckedChangeListener { buttonView, isChecked ->
    Log.d("RADIO", "Pirates is checked: $isChecked");
}

findViewById<RadioButton>(R.id.radio_ninjas).setOnCheckedChangeListener { buttonView, isChecked ->
    Log.d("RADIO", "Ninjas is checked: $isChecked");
}

在這個範例中,當使用者輕觸其中一個圓形按鈕時,Logcat 就會顯示訊息。