java - 以编程方式生成动态 RadioGroup 并对其进行 setOnCheckedChangeListener

标签 java android hashmap radio-button android-radiogroup

我编写了以下用于显示动态单选组和单选按钮的代码。 但我无法理解如何将选中的按钮放入 setOnCheckedChangeListener() 方法中。 有时多个 RadioButton 会点击同一个 RadioGroup。 不知道怎么办?

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll);

menuSize = 4;

for(i = 0; i < menuSize; i++)
{
    int menuId = controller.getMenuid(i));
    int subMenuSize = controller.getSubMenu(menuId).size();  // Dynamic value from MVC architechture

    TextView textViewHeading = new TextView(getApplicationContext()); // RadioGroup Heading
    textViewHeading.setText(controller.getMenuName(i));    // Set RadioGroup Heading

    linearLayout.addView(textViewHeading);

    RadioGroup radioGroup = new RadioGroup(getApplicationContext());
    radioGroup.setId(i);

    for(j = 0; j < subMenuSize; j++)
    {
        RadioButton radioButton = new RadioButton(getApplicationContext());

        radioButton.setId(j);

        // Get value from HashMap<Integer, ArrayList<SubMenuClass>>
        // Value is used for RadioButton
        radioButton.setText( controller.getSubMenu(menuId).get(j).getSubMenuName()); 

        radioGroup.addView(radioButton);
    }

    radioGroup.setOnCheckedChangeListener(TryRadioButtons.this);

    linearLayout.addView(radioGroup);
}

我想检查 ButtonSubmit Click,每个 RadioGroup 都有一个 RadioButton 必须检查。 那么如何在 ButtonSubmit ClickEvent 中获取 RadioButton?

提前致谢

最佳答案

这样做,

RadioGroup group = new RadioGroup(this); 
group.setOrientation(RadioGroup.HORIZONTAL);
RadioButton btn1 = new RadioButton(this);
btn1.setText("BTN1");
group.addView(btn1);
RadioButton btn2 = new RadioButton(this);
group.addView(btn2);
btn2.setText("BTN2");
.... 
RadioButton btnN = new RadioButton(this);
group.addView(btnN);
btnN.setText("BTNN");
yourLayout.addView(group);

关于java - 以编程方式生成动态 RadioGroup 并对其进行 setOnCheckedChangeListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29346549/

相关文章:

java - 如何覆盖单个按钮的 Nimbus 按钮边距

java - 方向改变是否会保留 gui 值并失去其余值

android - 布局膨胀后数据绑定(bind)方法何时触发?

java - 抽象类可以作为子类添加到HashMap中吗

Java - 构造函数明显缺失,运算符重载

java - 十六进制转换为 EBCDIC

java - 检查 key 是否在 map 中 - 一种方法有效,另一种方法无效

java - 从迭代中返回值列表

java - SLF4J 的 “dynamic binding” 功能什么时候适合使用?

android - 代码优化。 (建筑学)