I found here and here similar issues, but the problem is slightly different.
In a ListView, I try to put an adapter (extends from base Adapter) which contents checkb
I too had the same problem. I solved it using the following method.
I created a bean class to set the checked property of checkbox and used ArrayAdapter
.
The ArrayAdpater
extends the bean class.
public class MCSSCheckState
{
private boolean isChecked;
public boolean getIsChecked()
{
return isChecked;
}
public void setIsChecked(boolean isChecked)
{
this.isChecked = isChecked;
}
}
ArrayList<MCSSCheckState> mTitleList = new ArrayList<MCSSCheckState>();
MCSSCheckState check_state=new MCSSCheckState();
check_state.setIsChecked(false);
mTitleList.add(i, check_state);
ListAdapters adapter = new ListAdapters(this,R.id.camTitleTextView, mTitleList);
ListView mListView = (ListView) findViewById(R.id.cameraListView);
mListView.setAdapter(adapter);
private class ListAdapters extends ArrayAdapter<MCSSCheckState>
{
private ArrayList<MCSSCheckState> items;
private int position;
public ListAdapters(Context context, int textViewResourceId,
ArrayList<MCSSCheckState> mTitleList)
{
super(context, textViewResourceId, mTitleList);
this.items = mTitleList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
this.position = position;
if (v == null)
{
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.camerslistinflater, null);
}
MCSSCheckState o = (MCSSCheckState) items.get(position);
if (o != null)
{
checkBox = (CheckBox) v.findViewById(R.id.checkBox1);
checkBox.setTag(position);
checkBox.setChecked(o.getIsChecked());
checkBox.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
MCSSCheckState obj = (MCSSCheckState) items.get(Integer.parseInt(v.getTag().toString()));
obj.setIsChecked(((CheckBox)v).isChecked());
items.set(Integer.parseInt(v.getTag().toString()), obj);
}
});
}
return v;
});
}
Hope this helps you.
In your getView you have to something like this (this code is give you an idea how it will work in your case):
ListView lv = ((ListActivity)context).getListView();
// Containing all check states
SparseBooleanArray sba = lv.getCheckedItemPositions();
CheckBox cb = (CheckBox) convertView.findViewById(R.id.yourcheckbox);
cb.setChecked(false);
if(sba != null)
if(sba.get(position))
cb.setChecked(true);
That said this what you need on the Activity side.
You have make your ListView to multi-selection mode by android:choiceMode in xml or using setChoiceMode. You check box should be non-clickable and non-focusable.
You have to remove your onClick listener on buttons. Whatever you doing in onClick of button, you have to add that logic to the onListItemClick of ListActivtiy.