Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 701
ΧρησΤάκης Τσαν Avatar asked May 12 '12 17:05

ΧρησΤάκης Τσαν


People also ask

How do I add a radio group?

For this, open the “MainActivity. java” file and instantiate the components made in the XML file (RadioGroup, TextView, Clear, and Submit Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Button submit = (Button)findViewById(R.

Is it necessary to include multiple radio buttons in a radio group?

Radio buttons are normally presented in radio groups (a collection of radio buttons describing a set of related options). Only one radio button in a group can be selected at the same time.


1 Answers

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.)

like image 53
Sam Avatar answered Oct 20 '22 04:10

Sam