我已经创建了一个布局,它将膨胀到一个容器中,这个布局包含单选按钮
问题:布局膨胀但所有单选按钮都被选中,这是错误的吗?
包含要在容器中膨胀的单选按钮的布局。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="23dp"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
容器布局
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
代码给 child 充气
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0 ; i < 6 ; i++){
LinearLayout child =(LinearLayout) inflater.inflate(R.layout.layout_linear_with_rb,container,false);
container.addView(child);
}
最佳答案
radio 组 documentation
The selection is identified by the unique id of the radio button as defined in the XML layout file.
查看您的代码库,我发现您的 RadioButton 没有唯一的 ID。
我制作了一个示例项目并尝试使用唯一 ID 动态添加 RadioButton,它完美地工作。
RadioGroup container = findViewById(R.id.container);
for (int i = 0 ; i < 6 ; i++){
RadioButton radioButton = new RadioButton(this);
radioButton.setId(i);
container.addView(radioButton);
}
这种情况下可能会出现id冲突的问题。也许在其他 View 上设置了 0 的 id。为避免此类混淆,我建议使用 View.generateViewId() 生成唯一 ID。
View.generateViewId() 只能从 API >= 17 获得。
编辑 1
请停止在 RadioButton 布局中使用 LinearLayout 作为父级。一个快速修复方法是将 RadioButton 布局文件更改为
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
并将您的 Java 代码更改为
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0 ; i < 6 ; i++){
RadioButton radioButton = (RadioButton) inflater.inflate(R.layout.layout_linear_with_rb,container,false);
radioButton.setId(i);
container.addView(radioButton);
}
关于android - 将带有 RadioButton 的嵌套布局扩展到容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47809206/