我用radiobutton创建了动态放射性组。现在我想从动态放射性组中获取值。以下是我的代码
final RadioGroup rg = new RadioGroup(this);
rg.setId(questionNo);
RadioButton[] rb = new RadioButton[answers.length()];
for (int i = 0; i < answers.length(); i++) {
JSONObject answerObject = answers.getJSONObject(i);
rb[i] = new RadioButton(this);
rb[i].setText(answerObject.getString("AnswerValue"));
rb[i].setId(answerObject.getInt("AnswerId"));
rg.addView(rb[i]);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
int selectedId = rg.getCheckedRadioButtonId();
Log.i("ID", String.valueOf(selectedId));
}
});
按钮点击事件
submit_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(rg.getCheckedRadioButtonId()!=-1){
int id= rg.getCheckedRadioButtonId();
View radioButton = rg.findViewById(id);
int radioId = rg.indexOfChild(radioButton);
RadioButton btn = (RadioButton) rg.getChildAt(radioId);
String selection = (String) btn.getText();
Log.i("selection", selection);
}
}
});
我只收到广播组的最后一个索引。
答案 0 :(得分:1)
你可以通过这种方式解决这个问题
radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
void onCheckedChanged(RadioGroup rg, int checkedId) {
for(int i=0; i<rg.getChildCount(); i++) {
RadioButton btn = (RadioButton) rg.getChildAt(i);
if(btn.getId() == checkedId) {
String text = btn.getText();
// do something with text
return;
}
}
}
});
答案 1 :(得分:1)
我知道为时已晚,但这可能有助于其他人
创建动态Radiobutton组时,创建父布局(线性布局或相对布局)
所有广播组都将成为该版面的子节点,所有单选按钮都将成为特定广播组的子节点。
创建动态广播组的号码
将所有广播组添加到父版式
public RadioButton[] rb;
public RadioGroup grp;
public LinearLayout layoutmain; //Parent layout
for(int i=0;i<qus.size();i++) //No of Questions
{
rb = new RadioButton[size];
grp = new RadioGroup(this);
grp.setId(a+qus.get(i).qusetionId);
for(int j=0;j<qus.get(i).choices.size();j++) //No of Radio button in radio group
{
rb[j] = new RadioButton(this);
rb[j].setText(qus.get(i).choices.get(j).getChoiceText());
grp.addView(rb[j]); // adding button to group
}
layoutmain.addView(grp); // adding group to layout
}
检索所有选定的按钮任务
使用该对象获取所选单选按钮
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for(int i=0;i<layoutmain.getChildCount();i++) //From the parent layout (Linear Layout) get the child
{
View child = layoutmain.getChildAt(i);
if(child instanceof RadioGroup) //Check weather its RadioGroup using its INSTANCE
{
RadioGroup rg = (RadioGroup) child; //create a RadioButton for each group
int selectedId = rg.getCheckedRadioButtonId(); // get the selected button
RadioButton radiochecked = (RadioButton) findViewById(selectedId);
Log.e("Radio",radiochecked.getText().toString()); //from the button get the selected text
}
}
} });