我已经像下面这样动态地添加了单选按钮。
for (int i = 0; i< typeArrayList.size(); i++) {
radioButtons[i] = new RadioButton(MainActivity.this);
radioButtons[i].setId(i);
radioButtons[i].setText(typeArrayList.get(i).toString());
if(i==0) {
radioButtons[i].setChecked(true);
}
typeLayout.addView( radioButtons[i]);
}
当单击时我有一个按钮调用一个方法,动态添加的单选按钮的选定项目(文本)应该传递到该方法。如何获取动态添加的单选按钮的选定单选按钮文本?
最佳答案
在向单选组添加按钮时设置单选按钮 ID 非常重要。
RadioButton rb = new RadioButton(context);
rb.setText(option);
rb.setId(rb.hashCode());
radioGroup.addView(rb);
radioGroup.setOnCheckedChangeListener(mCheckedListner);
现在在您的点击监听器中检查唯一 ID。
private RadioGroup.OnCheckedChangeListener mCheckedListner = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
JSONArray actionArray = new JSONArray();
if(group.findViewById(checkedId)!=null) {
RadioButton rb = ((RadioButton) group.findViewById(checkedId)).getText();
//Your Code here
}
}
}
};
关于android - 如何获取动态添加的单选按钮的选定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38629378/