Android ユーザーインターフェース応用 ウィジェット RadioButton,CheckBox 【Android Tips】
RadioButtonとCheckBox
1
Android ユーザーインターフェース応用
ウィジェット RadioButtonとCheckBox
この章ではAndroidのウィジェットであるRadioButtonとCheckBoxについて解説していきます。
RadioButton
ラジオボタンはRadioGroupとRadioButtonウィジェットを使用し、相互排他(1つが有効で他が無効)のラジオボタンを作成します。
java.lang.Object
→android.view.View
→android.widget.TextView
→android.widget.Button
→android.widget.CompoundButton
→android.widget.RadioButton
java.lang.Object
→android.view.View
→android.widget.TextView
→android.widget.Button
→android.widget.CompoundButton
→android.widget.RadioButton
クラスの定義は上記のようになっており、RadioButtonクラスはCompoundButtonクラスのサブクラスとなります。このRadioButtonは、RadioGroupと共に用いるのが一般的です。RadioGroupタグで囲まれているRadioButtonが一つのグループとなり、その中で一つだけ選択できるようになります。下記コードで確認してみましょう。
レイアウトxmlファイル
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | < RadioGroup android:id = "@+id/radioGroup1" android:layout_width = "fill_parent" android:layout_height = "wrap_content" > < RadioButton android:id = "@+id/radioButton1" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentLeft = "true" android:layout_alignParentRight = "true" android:layout_alignParentTop = "true" android:text = "ON" /> < RadioButton android:id = "@+id/radioButton2" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentLeft = "true" android:layout_alignParentRight = "true" android:layout_below = "@+id/radioButton1" android:text = "OFF" /> </ RadioGroup > |
このxmlファイルを確認すると、2つのRadioButtonを1つのRadioGroupとしていることがわかります。
javaファイル
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 | package com.example.radiobutton; import android.app.Activity; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1); radioGroup.setOnCheckedChangeListener( new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton radioButton = (RadioButton) findViewById(checkedId); Toast.makeText(MainActivity. this , radioButton.getText() + "を選択しました。" , Toast.LENGTH_SHORT).show(); } }); } } |
次にjavaファイルを確認してみましょう。まず17行目でRadioGroupをインスタンス化しています。
RadioButtonをインスタンス化していないことがポイントです。
21行目にあるonCheckedChanged()はOnCheckedChangeListener()のコールバックメソッドで、RadioGroupのチェック状態が変換された時に呼び出されます。また、RadioButtonで用いるonCheckedChanged()の引数は以下の2つです。
- group:実際にクリックしたRadioButtonオブジェクトが含まれるRadioGroupオブジェクト
- checkedId:選択されたRadioButtonのID
このIDの値により各RadioButtonごとの処理を記述することが可能です。
今回の例では場合分けをせずに、クリックされたRadioButtonのテキストを取り出し、Toastに表示させています。