Reputation: 319
This is my first post on this website and i hope it is well done. I am trying to have a single selection in my radiogroup but all of them get selected and cannot be unchecked. I want if one radio button is selected, the others remain unchecked. Here is my code so far.
for (int row = 0; row < 1; row++) {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
for (int i = 1; i <= repItem.length; i++) {
final RadioButton rdbtn = new RadioButton(this);
rdbtn.setId((row * 2) + i);
rdbtn.setText(repItem[i-1]);
ll.addView(rdbtn);
final RadioButton rd=new RadioButton(this);
rdbtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
unCheckOther(rd, rdbtn.getId());
}
private void unCheckOther(RadioButton rd, int id)
{
for (int row = 0; row < 1; row++) {
for (int i = 1; i <= repItem.length; i++) {
int butId=((row * 2) + i);
if(butId != id)
{
rd.setChecked(false);
}
}
}
}
});
}
((ViewGroup) findViewById(R.id.radiogroupchoi)).addView(ll);
}
Kind regards
Upvotes: 1
Views: 467
Reputation: 9477
what you need is RadioGroup
. I see you have used a linearLayout
and add all radio buttons into that. that's not what you want. you can just simply change that linear layout to RadioGroup
.
Upvotes: 0
Reputation: 1699
You should use a RadioGroup instead of a LinearLayout
as the container. It will take care of the mutual exclusion.
Upvotes: 2