Do what you want to do

プログラミングとかとか

RadioButton, RadioGroup を使ってみる

今回はラジオボタンを使ってみます。

開発環境

レイアウト

まずはレイアウト。 ラジオボタンを2つ縦に並べてみました。 RadioButtonRadioGroupの中にいれてやることで 2つのラジオボタンを排他的(どちらか一方のみ選択可能)にできます。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.MainActivity">
    <RadioGroup
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/radioGroup" android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="8dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp">
        <RadioButton
                android:text="@string/radiobutton1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/radioButton1"
                app:layout_constraintEnd_toEndOf="@+id/radioGroup"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toTopOf="@+id/radioGroup"
                app:layout_constraintStart_toStartOf="@+id/radioGroup"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:onClick="onRadioButtonClicked"/>
        <RadioButton
                android:text="@string/radiobutton2"
                android:layout_height="wrap_content"
                android:id="@+id/radioButton2"
                android:layout_width="match_parent"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                android:onClick="onRadioButtonClicked"/>
    </RadioGroup>
</android.support.constraint.ConstraintLayout>

onClickイベントを実装する

レイアウトのxmlandroid:onClick="onRadioButtonClicked"の記述がありますが、ここでActivity側のクリックイベントハンドラーと紐づけています。 Activity側のメソッドがこちらです。

fun onRadioButtonClicked(view: View) {
    if (view is RadioButton) {
        val checked = view.isChecked

        when (view.id) {
            R.id.radioButton1 ->
                if (checked) {
                }
            R.id.radioButton2 ->
                if (checked) {
                }
        }
    }
}

viewのidからどちらのラジオボタンのイベントかどうかを判定しています。

実行結果

radiobutton

参考