[Android] RadioButton:ラジオボタンを表示する

ラジオボタンとは、いくつかある項目から1つを選択する時に使われるコンポーネントです。ここではラジボタンの表示方法について説明します。
広 告
目次
前提条件
動作確認端末
- Google Nexus 7 – 5.1.1 – API22(実機)
1. RadioButtonの概要
ラジオボタンを表示させるためにはRadioGroupクラスとRadioButtonクラスか、<RadioGroup>
タグと<RadioButton>
タグを使います。
Button クラスを継承しているため、Buttonクラスのメソッドを使用することが可能です。また<Button>
タグで使える属性も使用することが可能です。
2. ラジオボタンを表示する
レイアウトXMLでラジボタンを表示させるためには、<RadioGroup>
タグとを<RadioButton>
タグを使用します。ラベルに表示するテキストはandroid:text
属性で指定します。
レイアウトXMLを使用してラジオボタンを表示するためには以下の記述をします。
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 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" android:layout_alignParentTop="true" android:orientation="vertical" > <RadioButton android:id="@+id/radio_good" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="良い" /> <RadioButton android:id="@+id/radio_normal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="普通" /> <RadioButton android:id="@+id/radio_bad" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="悪い" /> </RadioGroup> </RelativeLayout>
<RadioButton>
タグを記述することでラジオボタンが表示されるようになります。ラジオボタンは複数の項目から1つ選択するためのコンポーネントであるため、選択肢の項目を<RadioGroup>
タグで囲ってあげる必要があります。
アプリを実行すると以下のようにラジオボタンが画面に表示されます。

Javaコードでチェックボックスを扱うためにはRadioGroupクラスとRadioButtonクラスを使用します。ラベルに表示するテキストはsetText()メソッドで設定します。
以下にsetText()メソッドの使用例を示します。
MainActivity.java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final RadioButton radioGood = (RadioButton) findViewById(R.id.radio_good); final RadioButton radioNormal = (RadioButton) findViewById(R.id.radio_normal); final RadioButton radioBad = (RadioButton) findViewById(R.id.radio_bad); radioGood.setText("Good!!"); radioNormal.setText("Normal"); radioBad.setText("Bad!!"); } }
アプリを実行すると以下のようにラジオボタンのラベルが変更されます。

3. 参考URL
RadioGroup | Android Developers
http://developer.android.com/intl/ja/reference/android/widget/RadioGroup.html
RadioButton | Android Developers
http://developer.android.com/intl/ja/reference/android/widget/RadioButton.html