【问题标题】:Generate dynamic RadioGroup programatically and setOnCheckedChangeListener on it以编程方式生成动态 RadioGroup 并在其上设置 OnCheckedChangeListener
【发布时间】:2015-06-03 11:43:28
【问题描述】:

我为显示动态单选组和单选按钮制作了以下代码。 但我不明白如何将检查按钮放入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?

提前致谢

【问题讨论】:

  • 你必须从第一行的线性布局开始,然后循环遍历它的子元素。
  • 我想在 setOnCheckedChangeListener() 方法中获取单选按钮
  • 是的,我知道。我已经知道了。你不必再说一遍。你对我的建议做了什么?
  • 我解决了。在我的代码中,setId 有问题。我将 ID 设置为“i”和“j”的值,这可能会在一段时间内相同。所以它会检查同一个单选组中的多个单选按钮。顺便感谢您的回复。

标签: java android hashmap radio-button android-radiogroup


【解决方案1】:

Refer this..

可能会帮助您动态获取单选按钮

【讨论】:

    【解决方案2】:

    这样做,

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

    【讨论】:

      猜你喜欢
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多