[英]Android dynamic radiobuttons id
我正在創建一個RadioButton
的數量(計數)。 我不能使用RadioGroup
,因為每個TableRow
的Button
旁邊需要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設置為5000
到5000 + (count - 1)
( RadioButton
數組具有count
的大小,但是這些ID直到count - 1
因為您從0
(?!?)開始循環。 在else
子句中,查找id 5000 + count
的RadioButton
,它在布局中不存在,因此最終以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.