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

Android RadioButton 單選按鈕的使用與取值

編輯:關於 Android 程式設計

RadioButton 需要和 RadioGroup 搭配使用才能發揮作用:RadioGroup 負責管理「同一組只能選一個」的互斥邏輯,RadioButton 則是具體的選項。取值時有兩種常見思路,一是遍歷分組的子控件找出被選中的那個,二是用 getCheckedRadioButtonId() 直接拿 ID。下面用最直觀的遍歷方式演示。

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

/**
 * RadioButton 示例
 */
public class MainActivity extends Activity implements OnClickListener {

    private Button button;
    private RadioGroup group;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        group = (RadioGroup) this.findViewById(R.id.sex);
        button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 獲得單選按鈕組的選項個數
        int len = group.getChildCount();
        String msgsString = "";
        for (int i = 0; i < len; i++) {
            RadioButton radioButton = (RadioButton) group.getChildAt(i);
            if (radioButton.isChecked()) {
                msgsString = radioButton.getText().toString();
                break;
            }
        }
        Toast.makeText(MainActivity.this, msgsString, 1).show();
    }
}

代碼邏輯很樸素:拿到 RadioGroup 的所有子 View,逐個判斷 isChecked(),命中後取出 text 並跳出循環,最後用 Toast 彈出結果。

幾個實用補充

如果選項是靜態寫在佈局裡的,用 group.getCheckedRadioButtonId() 會更乾淨,不必遍歷:

int checkedId = group.getCheckedRadioButtonId();
if (checkedId != -1) {
    RadioButton rb = (RadioButton) findViewById(checkedId);
    String text = rb.getText().toString();
}

另外兩個場景中也常用到的 API:

  • 監聽選中變化:給 RadioGroup 設置 setOnCheckedChangeListener,在 onCheckedChanged(group, checkedId) 裡即時響應用戶切換。
  • 默認選中:在佈局中給某個 RadioButton 加上 android:checked="true",或在代碼裡調用 group.check(R.id.xxx)。

順帶一提,Toast 的第三個參數是時長常量,應該傳 Toast.LENGTH_SHORT 或 Toast.LENGTH_LONG,示例裡直接寫 1 並不規範,實際開發時別照抄。

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