ΧρησΤάκης Τσαν ΧρησΤάκης Τσαν - 26 days ago 11
Android Question

How to add radio buttons to radio group

I have a TableLayout and in the third column of every row I want to place a radio group.
I build the RadioButtons like this:

rg = (RadioGroup) findViewById(R.id.radioGroup1);

for (int k = 0; k < size; k++) {
rb[k] = new RadioButton(context);
rg.addView(rb[k]);
}


However this cause my app to crash, any ideas?

Sam Sam
Answer

You are building a primitive array with the length of megethos, but your loop uses the length size. If megethos and size are different values this can cause many different types of errors... But all of this redundant since a RadioGroup keeps this array up to date for you.

I would try something like this:

RadioGroup group = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton button;
for(int i = 0; i < 3; i++) {
    button = new RadioButton(this);
    button.setText("Button " + i);
    group.addView(button);
}

And when you want to reference a button at index:

group.getChildAt(index);

Also please always post your logcat errors, it tells us exactly what went wrong and where to look. Otherwise we have to guess like this.

Update

The error is because you are trying to add the same button to two different layouts:

tr[k].addView(rb[k]);
rg.addView(rb[k]);

a view can only have one parent. As far as I know you cannot break a RadioGroup apart into multiple views without a lot of customization first. However a ListView already has the built-in feature setChoiceMode() that behaves like a RadioGroup:

List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, list);
ListView listView = (ListView) findViewById(R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setAdapter(adapter);

You can easily adapt simple_list_item_checked to display the SSID and signal strength. Hope that helps. (If you wait long enough imran khan might cut & paste my answer with graphical change, then claim it as his own again.)

Comments