簡體   English   中英

Android動態單選按鈕ID

[英]Android dynamic radiobuttons id

我正在創建一個RadioButton的數量(計數)。 我不能使用RadioGroup ,因為每個TableRowButton旁邊需要1個RadioButton 但是,與所有RadioButton ,一次只能選擇一個。 我想我可以設置id並在onCheckedChanged上讀取它,以更改所有內容,但將您單擊的內容更改為false。

rb = new RadioButton[count];

For-loop....
     rb[i]  = new RadioButton(this);
     rb[i].setId(5000 + i);
     rb[i].setOnCheckedChangeListener(this);

onCheckedChanged

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
{       
    for (int i = 0; i < count; i++)
    {
        if (buttonView.getId() == 5000 + i)
        {
            // Its the one
        }
        else
        {
            // Its not the one
            RadioButton rb = (RadioButton) findViewById((5000 + count));
            rb.setChecked(false);
        }
    }
}

.setChecked(false)抓住了正確的RadioButton ,但是當我嘗試.setChecked(false)它給了我NullPointerException ,我不知道為什么。

您正在將RadioButtons ID設置為50005000 + (count - 1)RadioButton數組具有count的大小,但是這些ID直到count - 1因為您從0 (?!?)開始循環。 else子句中,查找id 5000 + countRadioButton ,它在布局中不存在,因此最終以null引用結束。

編輯:

模擬RadioGroup的代碼應如下所示:

for循環中,您構建了RadioButtons

rb[i].setOnCheckedChangeListener(checkListener);
//...

其中checkListener是偵聽器實例:

private OnCheckedChangeListener checkListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            for (int i = 0; i < count; i++) {
                if (buttonView.getId() == 5000 + i) {
                    Log.e("XXX", "Position " + i);
                } else {                                       
                    RadioButton rb = (RadioButton) findViewById((5000 + i));
                    rb.setOnCheckedChangeListener(null);
                    rb.setChecked(false);
                    rb.setOnCheckedChangeListener(checkListener);
                }
            }
        }
    };

這是向您顯示NullPointerException,因為它沒有獲取選中的RadioButton的ID。而不是使用isCheked()方法來檢查天氣單選按鈕是否被選中。

  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
 {       
    for (int i = 0; i < count; i++)
  {
    if (buttonView.isChecked())
    {
        // perform your task here
    }
    else
    {
        // Do something here.........
    }
}

}

希望這可以幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM