Only select only one radio button from listview
Keep the currently checked RadioButton
in a variable in your Activity
. In the OnClickListener
of your RadioButtons
do this:
// checks if we already have a checked radiobutton. If we don't, we can assume that
// the user clicked the current one to check it, so we can remember it.
if(mCurrentlyCheckedRB == null)
mCurrentlyCheckedRB = (RadioButton) v;
mCurrentlyCheckedRB.setChecked(true);
}
// If the user clicks on a RadioButton that we've already stored as being checked, we
// don't want to do anything.
if(mCurrentlyCheckedRB == v)
return;
// Otherwise, uncheck the currently checked RadioButton, check the newly checked
// RadioButton, and store it for future reference.
mCurrentlyCheckedRB.setChecked(false);
((RadioButton)v).setChecked(true);
mCurrentlyCheckedRB = (RadioButton)v;
Here's my code:
ListAdapter.java
public class ListAdapter extends BaseAdapter {
private Context context;
private String[] version;
private LayoutInflater inflater;
private RadioButton selected = null;
public ListAdapter(Context context, String[] version) {
this.context = context;
this.version = version;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return version.length;
}
@Override
public Object getItem(int position) {
return version;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View view, ViewGroup viewGroup) {
final Holder holder;
if (view == null) {
holder = new Holder();
view = inflater.inflate(R.layout.row_list, null);
holder.radioButton = (RadioButton) view.findViewById(R.id.radio1);
holder.textViewVersion = (TextView) view.findViewById(R.id.textView1);
holder.btnMore = (Button) view.findViewById(R.id.button1);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.textViewVersion.setText(version[position]);
//by default last radio button selected
if (position == getCount() - 1) {
if (selected == null) {
holder.radioButton.setChecked(true);
selected = holder.radioButton;
}
}
holder.radioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (selected != null) {
selected.setChecked(false);
}
holder.radioButton.setChecked(true);
selected = holder.radioButton;
}
});
}
private class Holder {
private RadioButton radioButton;
private TextView textViewVersion;
private Button btnMore;
}
}
Hope this helps you :)