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

【Android入門】ラジオボタン(RadioButton)の使い方を実装例つきで徹底解説

このチュートリアルでは、Androidアプリでラジオボタン(RadioButton)を使用する方法を、サンプルコードとともにステップごとに解説します。ラジオボタンは「男性・女性」のように、複数の選択肢から1つだけを選ばせたい場合に最適なUIパーツです。RadioGroupでラジオボタンをグループ化することで、同時に1つしか選択できない状態を簡単に実現できます。

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

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

ステップ2:レイアウトファイル(activity_main.xml)を編集する

次に、res/layout/activity_main.xml に以下のコードを追加します。ここでは、RadioGroupの中に「Male(男性)」「Female(女性)」の2つのRadioButtonを配置し、その下に結果を表示するためのButtonを設置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <RadioGroup
        android:id="@+id/radioGender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">
    <RadioButton
        android:id="@+id/radioMale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/radioMale"
        android:checked="true" />
    <RadioButton
        android:id="@+id/radioFemale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/radioFemale" />
    </RadioGroup>
    <Button
        android:layout_below="@id/radioGender"
        android:id="@+id/btnDisplay"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnDisplay" />
</RelativeLayout>

ポイントは2つあります。android:checked="true" を指定すると、そのラジオボタンが初期状態で選択された状態になります。また、ラジオボタンをRadioGroup内にまとめることで、ユーザーは一度に1つの選択肢しか選べなくなります。

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

src/MainActivity.java に以下のコードを記述します。ボタンがクリックされると、getCheckedRadioButtonId() メソッドで現在選択されているラジオボタンのIDを取得し、そのテキストをToastで表示する仕組みです。

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.Toast;
public class MainActivity extends AppCompatActivity {
    RadioGroup radioGroup;
    RadioButton radioButton;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addListenerButton();
    }
    private void addListenerButton() {
        radioGroup = findViewById(R.id.radioGender);
        button = findViewById(R.id.btnDisplay);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedID = radioGroup.getCheckedRadioButtonId();
                radioButton = findViewById(selectedID);
                Toast.makeText(MainActivity.this, radioButton.getText(),Toast.LENGTH_SHORT).show();
            }
        });
    }
}

なお、最近のAndroid Studioで新規プロジェクトを作成した場合は、サポートライブラリの android.support.v7.app.AppCompatActivity の代わりに、AndroidXの androidx.appcompat.app.AppCompatActivity をimportしてください。

ステップ4:strings.xml に文字列リソースを追加する

res/values/strings.xml を開き、以下のコードを追加します。文字列をリソースファイルとして分離しておくことで、後からの修正や多言語対応が格段に楽になります。

<resources>
    <string name="app_name">sample</string>
    <string name="radioMale">Male</string>
    <string name="radioFemale">Female</string>
    <string name="btnDisplay">Display</string>
</resources>

ステップ5:AndroidManifest.xml を確認・編集する

最後に、androidManifest.xml に以下のコードを追加します。ここでは MainActivity がランチャーアクティビティとして登録されています。

<?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スマートフォンをPCに接続しているものとします。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。デバイス選択画面で自分のモバイル端末を選択すると、端末に以下のような初期画面が表示されます。

【Android入門】ラジオボタン(RadioButton)の使い方を実装例つきで徹底解説

画面上のボタンをタップすると、選択中のラジオボタンのテキスト(Male または Female)がToastメッセージとして画面下部に表示されます。これで、Androidにおけるラジオボタンの基本的な実装は完了です。アンケートフォームや設定画面など、さまざまな場面で応用してみてください。

  1. AndroidのラジオボタンにOnClickListenerを設定する方法【サンプルコード付きで解説】

    はじめに このチュートリアルでは、Androidアプリのラジオボタン(RadioButton)にクリックイベントを設定する方法を解説します。レイアウトXMLのandroid:onClick属性を利用すれば、JavaコードでsetOnClickListener()を明示的に呼び出すことなく、クリック時の処理をシンプルに実装できます。 今回は「ドライブしたい車を選ぶ」というサンプルアプリを通じて、実装手順をステップごとに見ていきましょう。 手順1:新規プロジェクトを作成する まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を

  2. 【Android】ScrollViewでスクロールバーを実装・カスタマイズする方法

    はじめにこの記事では、AndroidアプリでScrollView(スクロールビュー)を使用して、画面の内容が収まらない場合でも上下にスクロールできるようにする方法を、実際のコード例とともにステップ形式で解説します。あわせて、android:scrollbarSize属性を使ってスクロールバーの太さを変更する方法も紹介します。ステップ1:新規プロジェクトを作成するまず、Android Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な設定項目をすべて入力し、プロジェクトのセットアップを完了させてください。ステップ2:acti