同一片段/布局上的多个单选按钮和单选按钮标识符 - 如何为每个单选按钮设置唯一的计数器



我有 3 个无线电组在相同的布局和片段中。它们被定义为:

<RadioGroup
        style="@style/AppRadioGroup"
        android:id="@+id/p1_rg_company"
        android:layout_below="@id/textview3">
        <RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg2_o1" />
        <RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg2_o2" />
        <RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg2_o3" />
        <RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg2_o4" />
    </RadioGroup>
    <RadioGroup
        style="@style/AppRadioGroup"
        android:id="@+id/p1_rg_location">
        <RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg3_o1" />
        <RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg3_o2" />
        <RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg3_o3" />
        <RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg3_o4" />
    </RadioGroup>

一切正常,但是我有点惊讶地发现,当通过setOnCheckedChangeListener使用它们时,返回的值是单选按钮总数中的整数

代码如下:

RadioGroup rgLocation = (RadioGroup) frg_view.findViewById(R.id.p1_rg_location);
    rgLocation.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            Log.v(tag, Integer.toString(i)
        }
    });

因此,第一组返回从 1 到 4 的整数,第二组返回从 5 到 8 的整数。我的应用程序是 API16

我的期望和必要性是每个组都有一个单独的"计数器",因此每个组都有一个从 1 到 4 的值(由于数据模型,我需要这个值)。

我做错了什么吗,可以修复吗?

我无法从谷歌找到有关此行为的任何参考信息

如前所述,onCheckedChanged 返回的 int 是按钮的 id:

public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (radioGroup.getCheckedRadioButtonId() == i){
            Log.v(TAG, "Equal" );
            }
        }

在我看来,解决方法很蹩脚,但想不出更好的主意。

在 XML 布局中,我为每个按钮定义一个数字标记,其顺序如下:

<RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg2_o3"
            android:tag="3"/>
        <RadioButton
            style="@style/AppRadioButtons"
            android:text="@string/p1_rg2_o4"
            android:tag="4"
            />

然后在代码中:

public void onCheckedChanged(RadioGroup radioGroup, int i) {
         View v = getView().findViewById(i);
         int rbSelection = (int) v.getTag();
         dataObject.setPropertySelection(rbselection);
         }
    }

调用 findviewbyid 似乎是一种浪费,从标签中获取单个 int,这将使从数据库填充控件所需的代码复杂化,因为每个标签都需要映射到一个 id。

但是,如果有人知道如何改进这一点,并且只是通过单选组中的订单单击哪个单选按钮,请这样做。

最新更新