[Kotlin] RadioButtonの表示と選択処理

複数の選択肢から1つだけ選んでもらいたい場合には、ラジオボタンを利用するのが効果的です。
本稿ではRadioButtonについて解説します。

今回のサンプルコードはこちらです。

ラジオボタンを表示したい場合には、レイアウトで以下のような定義を行います。

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.buildbox.sample.buildbox_radiobutton.MainActivity">
 
    <RadioGroup
        android:id="@+id/color_group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:checkedButton="@+id/yellow_button">
 
        <RadioButton
            android:id="@+id/red_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="赤"/>
 
        <RadioButton
            android:id="@+id/yellow_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="黄"/>
 
        <RadioButton
            android:id="@+id/blue_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="青"/>
    </RadioGroup>
</RelativeLayout>

RadioButtonのみでも画面上にRadioButtonを表示して制御することは可能ですが、RadioGroupも合わせて使うことでグループ化ができるため、グループ内で選ばれたボタンを識別して処理を行いたい場合にはこちらのほうが適して居ます。
RadioGroupでandroid:checkedButtonにグルーピングしたボタンのうち一つ指定することで、画面が表示された時に選択された状態で表示されます。

選択されたときの処理はソース上で以下のように実装することとなります。
MainActivity.kt

1
2
3
4
5
6
7
8
9
val colorGroup: RadioGroup = findViewById(R.id.color_group)
colorGroup.setOnCheckedChangeListener { _, checkedId: Int ->
    when (checkedId) {
        R.id.red_button -> Toast.makeText(this, "赤色が選ばれています", Toast.LENGTH_SHORT).show()
        R.id.yellow_button -> Toast.makeText(this, "黄色が選ばれています", Toast.LENGTH_SHORT).show()
        R.id.blue_button -> Toast.makeText(this, "青色が選ばれています", Toast.LENGTH_SHORT).show()
        else -> throw IllegalArgumentException("not supported")
    }
}

Kotlinでの実装ですが、ポイントは2行目のsetOnCheckedChangeListenerです。ラジオボタンがクリックされた時、状態が変わったらイベントリスナーでイベントがコールバックされます。
RambdaでOnCheckedChangeListenerクラスの生成コードは省略されていますが、更にKotlinの機能で、本来の第一引数に渡されるRadioGroupは今回の実装では使っていないため、_ で省略を行っています。

他のところは一般的な実装ですが、一つの参考となれば幸いです。

「[Kotlin] RadioButtonの表示と選択処理」への7件のフィードバック

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください