简体   繁体   English

所有单选按钮都在一个无线电组,android下被选中

[英]All radio buttons are getting selected under a radio group, android

I'm very new to android and I have an xml like this: 我是android的新手,我有一个像这样的xml:

<RadioGroup
        android:id="@+id/cardRadioGroup"
        android:layout_width="wrap_content"
        android:layout_height="45dp" android:layout_alignParentLeft="true" android:layout_marginLeft="35dp"
        android:layout_alignTop="@+id/cardEditText">
</RadioGroup>

I'm tyring to inflate this xml using my code to generate as many radio buttons I want depending on my data model. 我打算根据自己的数据模型,使用我的代码为这个xml充气,以生成任意数量的单选按钮。

The code I use is (which is inside a for loop) : 我使用的代码是(在for循环中):

        LayoutInflater inflater = this.getLayoutInflater();
        View currentView = inflater.inflate(R.layout.card_payment_content_node,null);

        RadioGroup rg = (RadioGroup) currentView.findViewById(R.id.cardRadioGroup);
        RadioButton rb =  new RadioButton(this);
        //set radiobutton properties
        rb.setText(entry.getKey());
        rb.setId(++radioButtonIdCounter);

        rg.addView(rb);

        //add to view
        parent.addView(currentView);

This is working as expected. 这是按预期工作的。 But the problem is that I can select many radio buttons at a time on my device. 但问题是我可以在设备上一次选择多个单选按钮。

I'm not sure why this is happening. 我不确定为什么会这样。 Where I'm making the mistake? 我在哪里弄错了?

Thanks in advance. 提前致谢。

All of your buttons have the same ID. 您所有的按钮都具有相同的ID。 That's why they act so uniformly. 这就是为什么他们如此统一地行动。

You would inflate the layout only once. 您只需要膨胀一次布局。 You'd have to add the buttons programmatically by identifying cardRadioGroup and then looping in code, generating unique IDs for all buttons. 您必须通过识别cardRadioGroup以编程方式添加按钮,然后在代码中循环,为所有按钮生成唯一ID。

To add radio buttons to the group, use RadioGroup.addview() . 要将单选按钮添加到组,请使用RadioGroup.addview()

To create the radio buttons, use one of the constructors of RadioButton and set further properties if required. 要创建单选按钮,请使用RadioButton的构造函数之一,并根据需要设置其他属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM