abh22ishek abh22ishek - 2 months ago 13
Android Question

custom listview with only one checkbox is selected one at a time

I have a custom listview with each row contaning a checkbox and text. now what i want that if any one checkbox of listview row is checked so others checkbox in other row if checked .it will be delected automatically.(i.e only one checkbox should be selected one at a time).how should i do that.

So far what i have done is as follows:

public class CustomAdapter extends BaseAdapter{

Context context;
List<String> items;

boolean array[];


public CustomAdapter(Context context, List<String> items) {
super();
this.context = context;
this.items = items;
array =new boolean[items.size()];
}


@Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v=convertView;
final int pos=position;
if(v==null)
{
v=LayoutInflater.from(context).inflate(R.layout.list,null);
}

TextView txt1=(TextView) v.findViewById(R.id.textView1);
final CheckBox chkbox=(CheckBox) v.findViewById(R.id.checkBox1);

txt1.setText(items.get(position));
int selectedindexitem=0;
chkbox.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(chkbox.isChecked())
{
array[pos]=true;


}else{
array[pos]=false;
}
}
});
chkbox.setChecked(array[pos]);





return v;
}




}

In this code i can select multiple checkbox at a time but i need only one checkbox should be checked one at a time.

Answer

You need to keep track of selected item and code accordingly.

public class CustomAdapter extends BaseAdapter{
    Integer selected_position = -1;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
            // Your Code

            chkbox.setChecked(position==selected_position);

            chkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked)
                    {
                        selected_position =  position;
                    }
                    else{
                         selected_position = -1;
                    }
                    notifyDataSetChanged();
                }
            });
            return convertView;


        }
}