java - RadioButtons 在动态创建的 RadioGroup 中不能正确选择/取消选择

标签 java android radio-button radio-group

当我在 XML 布局文件中创建 RadioGroup 时,一切都很好,但是当我动态创建它时,RadioButtons 在选择另一个时不会取消选择:

enter image description here

代码如下:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);

    RadioButton radioButtonView = new RadioButton(this);
    radioButtonView.setText("RadioButton");
    radioGroup.addView(radioButtonView);

    RadioButton radioButtonView2 = new RadioButton(this);
    radioButtonView2.setText("RadioButton2");
    radioGroup.addView(radioButtonView2);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
}

布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true" >
</RadioGroup>
</RelativeLayout>

最佳答案

您需要为单选按钮设置某种 ID,例如:

int idRadio = <some number>;
radioButtonView.setId(idRadio++);
radioButtonView2.setId(idRadio++);

一旦它们具有不同的 ID,它就应该可以工作了。只需确保 ID 不与任何现有图形元素冲突,并且不为零(转到您的“gen”文件夹并查看 R.java 中的其他元素 ID)。

关于java - RadioButtons 在动态创建的 RadioGroup 中不能正确选择/取消选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13558045/

相关文章:

java - 如何在Java中实现嵌套集合的迭代器?

java - 不使用 wait 关键字同步块(synchronized block)是否安全?

当我尝试复制一个字符串时,Android NDK strcpy 崩溃

javascript - HTML/PHP : Pass multiple values based on one radio option

java - 将 AWS Lambda 函数放入 VPC,然后 "IOException: Connection reset by peer"开始发生,但只是偶尔发生

java - 将 ByteArrayOutputStream 转换为 BufferedImage

java - Android Studio 如果字段为空

javascript - 即使正在检查其中一个 radio ,表单仍然返回 false

html - 选择一个单选按钮后无法选择另一个单选按钮

java - Microsoft Windows Server 2003 中的 JRE 问题