[英]how to remove radio button items programmatically
在 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);
}
}
問題是這有時效果很好,但有時第一個單選按鈕仍未刪除。
PS稍后我想添加button2,它將為radiogroup提供不同的項目和不同的單選按鈕數量。 這就是為什么我需要在用戶進行選擇后刪除所有單選按鈕。
它真的很簡單,你只需這樣做:
rg.removeAllViews();
因為我使用了 for 循環,但它沒有刪除所有 RadioButtons。 玩得開心:)
我的第一個猜測是這部分代碼不好:
for (int i=0; i< rg.getChildCount(); i++){
rg.removeViewAt(i);
}
您不能在同時移除孩子的同時越過一個視圖的孩子(rg.getChildCount() 將在運行期間更改)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.