圓形按鈕可讓使用者從一組選項中選取一個選項。如果您認為使用者需要查看所有可用的選項並排列出,那麼針對互斥的選項組合,就應使用圓形按鈕。如果不需要並列顯示所有選項,請改用旋轉圖示。

在建立每個圓形按鈕選項時,請在版面配置中建立 RadioButton
。
不過,由於圓形按鈕彼此互斥,因此必須在 RadioGroup
內將這些按鈕設成一個群組。把它們設成一個群組,系統即可確保一次只能選取一個圓形按鈕。
主要類別如下:
回應點擊事件
當使用者選取其中一個圓形按鈕時,對應的 RadioButton
物件會收到一個點擊事件。
若要定義按鈕的點擊事件處理常式,請將 android:onClick
屬性新增至 XML 版面配置的 <RadioButton>
元素中。此屬性的值必須為回應點擊事件所用方法的名稱。接著,代管版面配置的 Activity
必須執行對應的方法。
例如,以下是一些 RadioButton
物件:
<?xml version="1.0" encoding="utf-8"?> <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android" 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="@string/pirates" android:onClick="onRadioButtonClicked"/> <RadioButton android:id="@+id/radio_ninjas" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/ninjas" android:onClick="onRadioButtonClicked"/> </RadioGroup>
注意:RadioGroup
是 LinearLayout
的子類別,其預設的方向為縱向。
在代管此版面配置的 Activity
中,下列方法會處理兩個圓形按鈕的點擊事件:
Kotlin
fun onRadioButtonClicked(view: View) { if (view is RadioButton) { // Is the button now checked? val checked = view.isChecked // Check which radio button was clicked when (view.getId()) { R.id.radio_pirates -> if (checked) { // Pirates are the best } R.id.radio_ninjas -> if (checked) { // Ninjas rule } } } }
Java
public void onRadioButtonClicked(View view) { // Is the button now checked? boolean checked = ((RadioButton) view).isChecked(); // Check which radio button was clicked switch(view.getId()) { case R.id.radio_pirates: if (checked) // Pirates are the best break; case R.id.radio_ninjas: if (checked) // Ninjas rule break; } }
在 android:onClick
屬性中宣告的方法必須具有與上述完全一致的簽章。具體來說,方法必須:
提示:如需自行變更圓形按鈕的狀態,請使用 setChecked(boolean)
或 toggle()
方法。