Androidでラジオボタン

Androidでラジオボタン

Androidでラジオボタンを使うには
RadioButtonを使う

RadioButtonはいくつでも設置できるけど
同グループと判断するためには
RadioGroupを使って
RadioButtonを覆う必要がある

このあたりはjQueryMobileやっていると
概念的にわかりやすい

まず、レイアウトファイルで
RadioGroupの中へ
RadioButtonを設置する

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
<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
 
<RadioButton
android:id="@+id/rbtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ボタン1"/>
 
<RadioButton
android:id="@+id/rbtn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="ボタン2"/>
 
<RadioButton
android:id="@+id/rbtn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ボタン3"/>
 
</RadioGroup>

次に、Javaでクリックイベント取得

RadioButtonのクリックイベント取得には
RadioButtonへ
setOnCheckedChangeListener
をセットして
クリックしたRadioButtonのidを判別する

1
2
3
4
5
6
7
8
9
10
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radiogroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
 
public void onCheckedChanged(RadioGroup group, int checkedId){
 
RadioButton rbtn = (RadioButton)findViewById(checkedId);
 
Toast.makeText(MainActivity.this, rbtn.getText()+"をタップしました", Toast.LENGTH_SHORT).show();
}
});

このように、処理するときにも
RadioGroupでまず判定して
そして各種ボタンが押されたときの処理を書く
今回は単純に押されたボタンをToastで表示

また、スマホの画面ではあまりやらなさそうだけど
タブレットなどの大きな画面で
ラジオボタンを横向にするなら
RadioGroupの
orientation=””
でhorizontalを設定すればいい

デフォルトでは、verticalなので縦向きになる

コメントを残す

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