2021年2月26日金曜日

Androidのラジオボタンを横並びにする

Androidアプリ開発でRadioButtonを使用する際
選択を変更したとき、他のチェック項目を自動で外す動作をさせるには
RadioButton達をRadioGroupにまとめておく必要がある。

しかし、RadioGroupに入れるとRadioButtonの配置が縦並びになってしまうので
横並びにする方法を記載する。

Designで編集する方法

赤枠内RadioGroupを選択する


右の赤枠にorientationという項目があるので、ここに「horizontal」に設定する


完成!


Codeで編集する方法

RadioGroupの「orientation」属性に「horizontal」を設定
  1. <RadioGroup
  2. android:layout_width="wrap_content"
  3. android:layout_height="wrap_content"
  4. android:orientation="horizontal">
  5.  
  6. <RadioButton
  7. android:id="@+id/radioButton"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:text="RadioButton" />
  11.  
  12. <RadioButton
  13. android:id="@+id/radioButton2"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:text="RadioButton" />
  17.  
  18. <RadioButton
  19. android:id="@+id/radioButton3"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:text="RadioButton" />
  23.  
  24. </RadioGroup>


理屈

公式のAPI仕様を確認するとわかるが、RadioGroupはLinearLayoutを継承している。
なので、デフォルトが縦並びになっている。
LinearLayoutは「orientation」属性で縦並び・横並びを変えることができるので、子クラスのRadioGroupも同じ理屈で変更ができる。

それにしても、
ラジオボタンは横並びが普通な気がするから、デフォルトを横並びにしても良いと思うのだが...

0 件のコメント:

コメントを投稿