简体   繁体   中英

How do I assign my dynamically created radio buttons in one group?

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;

  1. Never add any view more then once.
  2. When a View is already used (eg, you got it with findViewById, don't use addView on it. When you want to add a view, use addView with a NEW view.
  3. You can add several of these new views to one view, but you cannot add that one view multiple times.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM