【问题标题】:how to remove radio button items programmatically如何以编程方式删除单选按钮项目
【发布时间】:2012-09-14 20:52:44
【问题描述】:

在 xml 布局中,我有 RadioGroup、Button1、Button2。当用户点击 button1 时,会在 RadioGroup 中以编程方式创建几个单选按钮(单选按钮的总数可能不同(pocet = 要创建的单选按钮的数量)。

    final RadioButton[] rb = new RadioButton[pocet];        
    RadioGroup rg = (RadioGroup) findViewById(R.id.MyRadioGroup);

    radiobuttonCount++;
    for(int i=0; i<pocet; i++){
        rb[i]  = new RadioButton(this);
        rb[i].setText("Radio Button " + radiobuttonCount);
        rb[i].setId(radiobuttonCount+i);            
        rb[i].setBackgroundResource(R.drawable.button_green);            
        rg.addView(rb[i]);            
    }

我尝试做的是:当用户从 RadioGroup 中选择 xy 项目时,我会将所选值传递给 textview 并删除所有单选按钮。

出于删除目的,我使用:

        public void onCheckedChanged(RadioGroup rGroup, int checkedId)
        {
            RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
            boolean isChecked = checkedRadioButton.isChecked();
            if (isChecked)
            {
                RadioGroup rg = (RadioGroup)    findViewById(R.id.MyRadioGroup);                                        

                for (int i=0; i< rg.getChildCount(); i++){
                    rg.removeViewAt(i);
                }
            }

问题是这有时效果很好,但有时第一个单选按钮仍未删除。

附: 稍后我想添加 button2,它将为 radiogroup 提供不同的项目和不同的单选按钮数量。这就是为什么我需要在用户选择后删除所有单选按钮。

【问题讨论】:

    标签: android button dynamic radio


    【解决方案1】:

    我的第一个猜测是这部分代码不好:

       for (int i=0; i< rg.getChildCount(); i++){
            rg.removeViewAt(i);
        }
    

    您不能在移除子视图的同时碾过一个视图的子视图 (rg.getChildCount() 会在运行过程中改变)

    【讨论】:

      【解决方案2】:

      真的很简单,你只需这样做:

      rg.removeAllViews();
      

      因为我使用了 for 循环,但它并没有删除所有 RadioButtons。 玩得开心:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-19
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多