Reputation: 941
In my app,i am creating radio buttons dynamically and want to uncheck all other radio buttons when one of them is checked.For this purpose,i am using RadioGroup.clearCheck() but it is not working at all.This is the code:
for (int i=0; i<files.length; i++)
{
rbi = new RadioButton(context);
rb1 = new RadioGroup(context);
rb1.addView(rbi);
nameOfFile = files[i].getName();
rbi.setText(nameOfFile);
ll.addView(rb1);
rbi.setOnClickListener(
new RadioButton.OnClickListener()
{
@Override
public void onClick(View v)
{
rb1.clearCheck();
rbi.setChecked(true);
}
Please help me.Even the alternate solutions for achieving the goal will be welcomed.Thanks in advance.
Upvotes: 1
Views: 3854
Reputation: 63955
You create a lot of RadioGroup
s with just 1 RadioButton
inside. That is probably not what you want. A RadioGroup
needs to contain several RadioButton
s so you can select an active button inside the list. See code below
// create 1 RadioGroup, add it to the layout
RadioGroup rg = new RadioGroup(context);
ll.addView(rg);
// add several RadioButtons to the RadioGroup
for (int i=0; i < files.length; i++) {
String nameOfFile = files[i].getName();
RadioButton rb = new RadioButton(context);
rb.setId(i); // assign an id
rb.setText(nameOfFile);
rg.addView(rb); // add to group
}
// do something when user checks a button
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// user selected files[checkedId].getName();
}
});
Upvotes: 2
Reputation: 3666
Did you try (with System.out.println("test");) or something, if it even gets into the clearing part? Would test that first. This is what zapl means
rb1.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup rb1,
int checkedId) {
Log.v("Selected", "New radio item selected: " + checkedId);
}
});
if that works, then you can try this:
if (rbi.isChecked()){
rb1.clearCheck();
rbi.setChecked(true);
}
Upvotes: 1