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

Android 單選組件 RadioGroup 與 RadioButton 使用教學

編輯:關於 Android 開發

用 RadioGroup 實現單選效果

當需要讓使用者在多個選項中擇一時,RadioGroup 搭配 RadioButton 是最直覺的選擇。同一個 RadioGroup 內的單選按鈕會互斥,選了一個,其他會自動取消。

一、佈局 xml

<RadioGroup
    android:id="@+id/group1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="radio1" />
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="radio2" />
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="radio3" />
</RadioGroup>

<TextView
    android:text="你的選擇是:"
    android:id="@+id/txtResult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

二、Java 邏輯

為 RadioGroup 註冊 OnCheckedChangeListener,透過 getCheckedRadioButtonId() 取得被選中的按鈕,再把它的文字顯示到 TextView 上:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final TextView textView = (TextView) findViewById(R.id.txtResult);
    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.group1);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            int radioButtonId = radioGroup.getCheckedRadioButtonId();
            RadioButton rb = (RadioButton) findViewById(radioButtonId);
            textView.setText(rb.getText());
        }
    });
}

這樣一來,每當切換選項,下方的文字就會即時更新為目前所選的單選項,是表單類界面的基礎用法。

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