将带有 RadioButton 的嵌套布局扩展到容器

Inflating Nested Layout with RadioButton to a Container

我创建了一个布局,该布局将膨胀到一个容器中,此布局包含单选按钮

问题:布局膨胀但所有单选按钮都被选中,这是错误的吗?

包含要在容器中展开的单选按钮的布局。

<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);
    }

截图:RadioButton screenshot containing someview

广播组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冲突的问题。也许在其他视图上设置了 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);
}

这里的问题是 RadioGroup 它只查找 RadioButton 子项,因为我使用的是包含 RadioButton 的嵌套布局,所以 RadioGroup 找不到以编程方式扩展的 RadioButton。

我是如何解决这个问题的 https://github.com/worker8/RadioGroupPlus 这是一个深入挖掘嵌套布局并在其中找到 RadioButton 的 RadioGroup 调整。