i have a trouble with listview. i added a checkbox into listview to choose items. my data is coming from sqlite so i use simple cursor adapter. length of my list is aproximatley
Here is simple example that will help you to implement that scenario
http://www.mysamplecode.com/2012/07/android-listview-checkbox-example.html
If you have CheckBox
es in ListView
you have problem, because ListView
reuses View
s that aren't already visible on screen. That's why when you scroll down, it loads (a few times) that one CheckBox
that was checked by you previously. So you can't rely on default CheckBox
's behaviour. What you need is:
Prevent user from checking CheckBox
. You can do this by calling cb.setEnabled(false)
, where cb
is CheckBox
which you are using.
Create your own adapter class that will extend SimpleCursorAdapter
. In this class you will store list
of indexes of items that are checked.
Override getView()
method in your adapter class and there manually set CheckBox
to be checked if it's position is stored in checked items array.
Create OnClickListener
for your ListView
which will take care of adding/removing checked items' positions from adapter's internal array.
Edit:
This would be the code of your adapter:
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
public ArrayList<Integer> mItemsChecked;
public MySimpleCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
mItemsChecked = new ArrayList<Integer>();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
for(int i = 0; i < mItemsChecked.size(); i++) {
if(mItemsChecked.get(i) == position) {
CheckBox cb = (CheckBox)convertView.findViewById(R.id.checkBox1); // Instead of checkBox1, write your name of CheckBox
cb.setChecked(true);
}
}
return super.getView(position, convertView, parent);
}
/* Just a handy method that will be responsible for adding/removing
items' positions from mItemsChecked list */
public void itemClicked(int position) {
for(int i = 0; i < mItemsChecked.size(); i++) {
if(mItemsChecked.get(i) == position) {
mItemsChecked.remove(i);
return;
}
}
mItemsChecked.add(position);
}
}
This is OnItemClickListener
for your ListView
:
final ListView lv = (ListView)findViewById(R.id.listView1); // Your ListView name
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
((MySimpleCursorAdapter)lv.getAdapter()).itemClicked(position);
lv.getAdapter().notifyDataSetChanged(); // Because we need to call getView() method for all visible items in ListView, so that they are updated
}
});
Just remember to disable your CheckBox
so that user can't click it.
Now you can see it as a little hack, because user doesn't click CheckBox
at all - application sees it as clicking in specific ListView
item, which in turn automatically checks appropriate CheckBox
for you.