I have a code that generates an array of radio buttons and I want to know how to assign them in one group so the other radio buttons won't be enabled if another is enabled.
This here is my code for the generation of the said radio buttons.
for (int i = 0; i < 20; i++)
{
RadioButton myRadio = new RadioButton(this);//use array
myRadio.setId(i);
final int id_ = myRadio.getId();
myRadio.setText("button " + id_);
LinearLayout li = (LinearLayout)findViewById(R.id.buttonlayout);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
li.addView(myRadio, lp);
btn = (RadioButton) findViewById(id_);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Button clicked index = " + id_, Toast.LENGTH_SHORT).show();
}
});
}
btn is a button declared outside the function. It is also a radio button
Try this code sample
final RadioButton[] rb = new RadioButton[20];
RadioGroup rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.VERTICAL);
for(int i=0; i<20; i++){
rb[i] = new RadioButton(this);
rg.addView(rb[i]);
rb[i].setText(" " + ContactsActivity.phonetype.get(i)
+ " " + ContactsActivity.phone.get(i));
rb[i].setId(i + 100);
}
ll.addView(rg);//you add the whole RadioGroup to the layout
Update - Answer for the error you mentioned in your comments
To resolve your error, find out, using the line-number in the error, which line produces the error. Look at what you are adding there
Check all your addView calls. (hint: there is a line-number in that error somewhere. use it)
To try to answer your question in the comment, you must follow these rules;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.