androidcodehunter androidcodehunter - 3 months ago 34
Android Question

Only select only one radio button from listview

I have searched the question over and over, there are many questions I have found in stackoverflow but I did not come up with a solution. Here is my problem.
I have a list of item in a linearlayout like this:
enter image description here

When the screen comes first, the last radion button is selected automatically. But if I select another radio button, the last radio button is already in selected state. I want to select only one radion button but at the same time when the screen comes first the last radio button will be auto selected and other automatically will not be selected.
How can I achieve this.
My adapter class is :

public class AdapterPaymentMethod extends ArrayAdapter<PaymentData> {
private Context context;
private boolean userSelected = false;
ViewHolder holder;

public AdapterPaymentMethod(Context context, int resource,
List<PaymentData> items) {
super(context, resource, items);
this.context = context;

/* private view holder class */
private class ViewHolder {
RadioButton radioBtn;
Button btPaymentMethod;
// ImageView ivLine;

public View getView(final int position, View convertView, ViewGroup parent) {
holder = null;
PaymentData rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
if (convertView == null) {
convertView = mInflater.inflate(, null);
holder = new ViewHolder();
holder.radioBtn = (RadioButton) convertView
holder.btPaymentMethod = (Button) convertView
} else
holder = (ViewHolder) convertView.getTag();

if(position==getCount()-1 && userSelected==false){
Log.d("if position", ""+position);
Log.d("else position", ""+position);

holder.radioBtn.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
else if(getCount()-2==position&&userSelected==true)

return convertView;


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;

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

// Otherwise, uncheck the currently checked RadioButton, check the newly checked 
// RadioButton, and store it for future reference.
mCurrentlyCheckedRB = (RadioButton)v;