Android でラジオボタンの値を取得する方法は何ですか?

アンドロイドにおいて、ラジオボタンの値を取得する方法は以下の通りです:

  1. 最初に、レイアウトファイルでラジオボタングループ(RadioGroup)と複数のラジオボタン(RadioButton)を定義し、各ラジオボタンにはユニークなIDを設定します。
  2. Activity内で、RadioGroupオブジェクトを取得するためにfindViewByIdメソッドを使用し、OnCheckedChangeListenerリスナーを設定してラジオボタンの選択状態の変化を監視します。
  3. OnCheckedChangeListener のコールバックメソッド内で、getCheckedRadioButtonId メソッドを使用して選択されたラジオボタンの id を取得できます。
  4. 最後、選択したラジオボタンのidを組み合わせて、findViewByIdメソッドを使用して対応するRadioButtonオブジェクトを取得し、getTextメソッドを使用して表示されているテキスト値を取得できます。

以下は例のコードです。

レイアウトファイルでラジオボタングループとラジオボタンを定義します。

<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 1" />

    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 2" />

    <RadioButton
        android:id="@+id/radioButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 3" />

</RadioGroup>

Activity内でラジオボタンの値を取得する:

RadioGroup radioGroup = findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        RadioButton radioButton = findViewById(checkedId);
        String selectedValue = radioButton.getText().toString();
        // 处理选中的值
    }
});
bannerAds