Android
 Computer >> コンピューター >  >> プログラミング >> Android

AndroidでRadioGroupの選択されたインデックスを取得する方法【サンプルコード付き】

この記事では、AndroidアプリでRadioGroup(ラジオグループ)の中から選択されているRadioButtonのインデックスやテキストを取得する方法を、サンプルコードとともにステップ形式で解説します。

実装手順

ステップ1:新規プロジェクトを作成する

Android Studioを起動し、メニューから「File」⇒「New Project」を選択して、必要な項目を入力し新しいプロジェクトを作成します。

ステップ2:レイアウトファイル(activity_main.xml)にコードを追加する

res/layout/activity_main.xml に以下のコードを記述します。質問を表示するTextView、2つの選択肢(Netflix/Amazon Prime)を持つRadioGroup、そして選択結果を取得するためのButtonを配置しています。

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/tvResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="15dp" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Which is your most favorite?"
        android:textStyle="bold"
        android:textSize="16sp"
        android:layout_below="@+id/tvResult" />
    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_below="@id/textView"
        android:padding="15dp">
        <RadioButton
            android:id="@+id/rbNetflix"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Netflix"
            android:paddingRight="15dp" />
        <RadioButton
            android:id="@+id/rbAmazonPrime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Amazon Prime"
            android:paddingRight="15dp" />
    </RadioGroup>
    <Button
        android:id="@+id/btnGetItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Selected Radio Button"
        android:layout_below="@+id/radioGroup" />
</RelativeLayout>

ステップ3:MainActivity.java にコードを追加する

src/MainActivity.java に以下のコードを記述します。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button button;
    RadioGroup radioGroup;
    RadioButton selectedRadioButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.btnGetItem);
        radioGroup = findViewById(R.id.radioGroup);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedRadioButtonId = radioGroup.getCheckedRadioButtonId();
                if (selectedRadioButtonId != -1) {
                    selectedRadioButton = findViewById(selectedRadioButtonId);
                    String selectedRbText = selectedRadioButton.getText().toString();
                    textView.setText(selectedRbText + " is Selected");
                } else {
                    textView.setText("Nothing selected from the radio group");
                }
            }
        });
    }
}

コードのポイント:ボタンがクリックされると、radioGroup.getCheckedRadioButtonId() によって現在選択されているRadioButtonのリソースIDを取得します。何も選択されていない場合は -1 が返るため、この戻り値で未選択状態を判定できます。選択済みであれば、そのIDからRadioButtonインスタンスを取得し、getText() でラベル文字列を取り出してTextViewに表示しています。

※ 補足:本記事のコードは旧サポートライブラリ(android.support.v7.app.AppCompatActivity)を使用していますが、こちらは現在非推奨です。AndroidXを使用するプロジェクトでは、androidx.appcompat.app.AppCompatActivity に置き換えてください。

ステップ4:AndroidManifest.xml にコードを追加する

androidManifest.xml に以下のコードを記述します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

アプリを実行して動作を確認する

それではアプリを実行してみましょう。ここでは、実機のAndroidスマートフォンがパソコンに接続されているものとします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。デバイス選択ダイアログで接続したモバイルデバイスを選ぶと、実機に次のような画面が表示されます。

AndroidでRadioGroupの選択されたインデックスを取得する方法【サンプルコード付き】

AndroidでRadioGroupの選択されたインデックスを取得する方法【サンプルコード付き】

AndroidでRadioGroupの選択されたインデックスを取得する方法【サンプルコード付き】

  1. 【Android】エミュレータのIPアドレスを取得して表示する方法を解説

    はじめにこの記事では、Androidアプリから端末(エミュレータ/実機)のIPアドレスを取得し、画面に表示する方法を、実際のサンプルコードとともにステップ形式で解説します。Wi-Fi接続情報を利用したシンプルな実装例なので、Android開発初心者の方にもわかりやすい内容となっています。手順1:新規プロジェクトの作成まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。手順2:レイアウトファイル(activity_main.xml)の編集res/layout/acti

  2. Tkinter Comboboxで選択したオプションのインデックスを取得する方法

    ドロップダウンリストを作成し、ユーザーがリスト内の項目を選択できるようにしたい場合は、TkinterのComboboxウィジェットを使用します。Comboboxウィジェットを使うと、項目の一覧から瞬時に選択できるドロップダウンリストを簡単に実装できます。ここで重要なのが、ユーザーが選択した項目のインデックス(位置番号)を取得する方法です。これには current() メソッドを使用します。current()メソッドは、現在選択されている項目のインデックスを整数値として返します。なお、何も選択されていない状態では -1 が返される点にも注意してください。コード例実際に動作を確認してみましょう。こ