0
1

More than 3 years have passed since last update.

【Android】ラジオボタンを追加する方法

Posted at

プログラミング勉強日記

2020年12月26日
Androidアプリ開発でラジオボタンを作成したのでその方法を簡単にまとめる。

ラジオボタンを利用するときに使うクラスとメソッド

  • RadioButton
  • RadioGroup
  • onCheckedChangeListener
  • void check(int id)
  • int getCheckradioButtonId()
  • void clearCheck()

 
 RadioButtonはそれぞれの項目に相当するクラス。
 RadioGroupは複数のRadioButtonを持ち、それらの1つだけ選択できる。
 OnCheckedChangeListenerは選択されている項目が変わった時に通知を受ける。
 void check(int id)は引数で指定したラジオボタンを選択するメソッド。
 int getCheckradioButtonId()は選択中のラジオボタンのIDを取得するメソッド。
 void clearCheck()は選択を解除するメソッド。

ラジオボタンを配置する方法

 レイアウトエディタのパレットからRadioGroupを選択し、レビュー画面にドラッグする。次にRadioButtonをRadioGroupまでドラッグして追加する。

image.png

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="154dp"
        tools:layout_editor_absoluteY="212dp"
        tools:ignore="MissingConstraints">

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="RadioButton1" />

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

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="RadioButton3" />
    </RadioGroup>

</androidx.constraintlayout.widget.ConstraintLayout>

参考文献

ラジオボタンで複数の選択肢から1つを選択させる / GETTING STARTED
Androidアプリ開発でRadioButton(ラジオボタン)を追加する方法

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1