我有4 RadioButtons
这样安排:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<RadioButton
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"/>
<RadioButton
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 2"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<RadioButton
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 3"/>
<RadioButton
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 4"/>
</LinearLayout>
</LinearLayout>
</RadioGroup>
</RelativeLayout>
我的问题是,现在可以按下每个RadioButton
并一起选择。这不应该发生。必须始终选择一个或零RadioButtons
,而不是多个。在正常RadioGroup
中,不会发生此问题。我认为这是因为它中的LinearLayout's
,但我的应用程序的其余部分需要它们。我该如何解决这个问题?
如何以RadioButtons
的方式将RadioGroup
作为孙子孙女?
答案 0 :(得分:2)
我建议你不要在RadioGroup中使用嵌套的嵌套布局(线性/相对)来增加视图层次结构。此外,您将无法使用嵌套布局获得单一选择功能。 RadioGroup实际上扩展了LinearLayout。因此它只能垂直或水平排列RadioButtons。在这里,我分享了链接 RelativeRadioGroup 我的库实际上是一个RelativeRadioGroup,这样你就可以按照自己的意愿安排RadioButtons,特别选择不会受到影响。
答案 1 :(得分:1)
当您在LinearLayout
内使用RadioGroup
时,RadioGroup
会丢失其基本functionality
到toggle
按钮states
及其覆盖方法{ {1}}永远不会被召唤。
要解决此问题,您必须更改onCheckedChanged()
个州RadioButton
。
以下是完整的解决方案:
programmatically
<强>输出:强>
https://stackoverflow.com/a/36769278/1977315
希望这会有所帮助〜
答案 2 :(得分:0)
您无法在RadioGroup中放置任何其他布局。因此,如果您仍想将所有RadioButton放在线性布局中,您将需要做一些额外的工作。
以编程方式执行,当选中任何RadioButton时,将其他设置为未选中。
像
这样的东西RadioButton rbu1 =(RadioButton)findViewById(R.id.radio0);
RadioButton rbu2 =(RadioButton)findViewById(R.id.radio1);
rbu1.setOnClickListener(first_radio_listener);
rbu2.setOnClickListener(second_radio_listener);
OnClickListener first_radio_listener = new OnClickListener (){
public void onClick(View v) {
rbu2.setChecked(false);
}
};
OnClickListener second_radio_listener = new OnClickListener (){
public void onClick(View v) {
rbu1.setChecked(false);
}
};