RadioButtonのレイアウトをいじりたい
AndroidのRadioButtonを、標準の設定画面とかにあるみたいに
設定ボタンとか右っかわにおきたくなったんです。
こんな風に。
これは4.2からついたスクリーンセーバの画面ですが。
RadioButtonってRadioGroupに囲んで使うじゃないですか。
だから素直にこうしてみたんです。
<RadioGroup android:id="@+id/settingRadio" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <RadioButton android:id="@+id/radio0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="いち" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <RadioButton android:id="@+id/radio1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="に" /> <ImageView android:id="@+id/settings" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:src="@drawable/ic_sysbar_quicksettings" android:background="@drawable/clear_button_bg" /> </LinearLayout> </RadioGroup>
レイアウト自体は、まあ細かいことはさておき、
思った通りにできそうでした。
でも、RadioGroupがちゃんと動かない。。
どっちもチェックできちゃったり、イベントとしてradio1の方は拾えていないみたいです。
ちょっと調べると
android - Custom layout for RadioButton - Stack Overflow
の答えでRadioGroupをカスタムしないといけないよ、らしいです。
うーん。
Y.A.M の 雑記帳: Android TableLayout, RelativeLayout で RadioButton を使う
yanzmさんみたく簡単にできるかと思ったんですが、
ちょっとhideなメソッドとか呼んでいて面倒だったので、
android - How to group RadioButton from different LinearLayouts? - Stack Overflow
を参考にOnClickListenerをセットしてみたらとりあえずそれっぽく動きました。
ちょっとださいやり方ですが。。
時間あったらもうちょっと試したいですね。
RadioButton r0 = findViewById(R.id.radio0); RadioButton r1 = findViewById(R.id.radio1); r0.setOnClickListener(new OnClickListener() { public void onClick(View v) { r0.setChecked(true); r1.setChecked(false); } }); r1.setOnClickListener(new OnClickListener() { public void onClick(View v) { r0.setChecked(false); r1.setChecked(true); } });
RadioButtonってCompoundButtonを継承しているから
OnCheckedChangeListenerでもいいじゃないかと思いましたが、
onCheckedChangedでCompoundButtonがnullできちゃいました。。
なんででしょう。。。
あと、とりあえずLayoutもRadioGroupの機能使えないんで
わかりやすくLinearLayoutにしちゃいました。
<LinearLayout > <RadioButton /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <RadioButton /> <ImageView /> </LinearLayout> </LinearLayout>