我有一个无线电组,我按如下方式动态填充:
RadioGroup ll = new RadioGroup(this);
ll.setOrientation(RadioGroup.VERTICAL);
for (int i = 1; i <= repItem.length; i++) {
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId((row * 2) + i);
rdbtn.setText(repItem[i-1]);
ll.addView(rdbtn);
}
((RadioGroup) findViewById(R.id.radiogroupchoi)).addView(ll);
我得到一个点击事件,如下所示我想捕捉放射组中相关选定单选按钮的文本。但它给了我nullpointerexception。有什么帮助吗?
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
RadioGroup rChoi=(RadioGroup) findViewById(R.id.radiogroupchoi);
RadioButton butChoi=(RadioButton) findViewById(rChoi.getCheckedRadioButtonId());
Toast.makeText(getApplicationContext(),butChoi.getText(), Toast.LENGTH_SHORT).show();
}
});
答案 0 :(得分:0)
将您的代码更改为 -
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
RadioGroup rChoi=(RadioGroup) findViewById(R.id.radiogroupchoi);
RadioButton butChoi=rChoi.findViewById(rChoi.getCheckedRadioButtonId());
Toast.makeText(getApplicationContext(),butChoi.getText(), Toast.LENGTH_SHORT).show();
}
});
希望这会有所帮助:)
答案 1 :(得分:0)
您可以将RadioButtons直接添加到布局中的RadioGroup,而不是创建新的RadioGroup并将其作为子视图添加到现有的RadioGroup。所以只需找到RadioGroup并向其添加RadioButtons,如下所示:
RadioGroup ll = (RadioGroup) findViewById(R.id.radiogroupchoi);
ll.setOrientation(RadioGroup.VERTICAL);
for (int i = 1; i <= repItem.length; i++) {
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId((row * 2) + i);
rdbtn.setText(repItem[i-1]);
ll.addView(rdbtn);
}
NullPointerException可能是因为在R.id.radiogroupchoi中没有检查过的RadioButton,被检查的RadioButton实际上是你创建的RadioGroup并作为子视图添加到它。