Getting checkbox information from a listview
-
17-04-2021 - |
Question
I have an activity with a list fragment in it that has a layout with a checkbox for each row. I set the onclick
xml attribute for the checkbox and do the following for testing
public void onBoxClick(View v){
checkedItems = listview.getCheckedItemPositions();
int checkedItemsCount = checkedItems.size();
}
checkedItemsCount
comes back 0
, I thought to get what items that are checked you use the listview.getCheckedItemPositions()
but it is not so how do I know what is checked in the list?
this is my listfragment creation
@Override
public void onActivityCreated(Bundle state){
super.onActivityCreated(state);
listview = getListView();
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listview.setItemsCanFocus(false);
setEmptyText("No Bowlers");
registerForContextMenu(getListView());
populateList();
}
Solution 2
I got around the problem by Custom Adapter's bindView
, I created an ArrayList<Integer>
variable
ArrayList<Integer> mCheckedItems = new ArrayList<Integer>();
and In the bindView
I set a checkedchangelistener
on the checkbox to see if the box was checked or not. If it was checked I put the id from the database that the cursor got into the mCheckedItems Array
adapter:
public class CheckAdapter extends SimpleCursorAdapter{
Context context;
public CheckAdapter(Context context, int layout, Cursor c,String[] from, int[] to,int flag) {
super(context, layout, c, from, to);
this.context = context;
}
@Override
public void bindView(View view,Context context,Cursor cursor){
final String name = cursor.getString(cursor.getColumnIndex(BowlersDB.NAME));
final int id = cursor.getInt(cursor.getColumnIndex(BowlersDB.ID));
TextView tv = (TextView)view.findViewById(R.id.nameCheckTV);
tv.setText(name);
CheckBox cb = (CheckBox)view.findViewById(R.id.checkBox1);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
mCheckedItems.add(id);
}else if(!isChecked){
for(int i=0; i< mCheckedItems.size(); i++){
if(mCheckedItems.get(i) == id){
mCheckedItems.remove(i);
}
}
}
}
});
}
After the id was inserted into the array I used the array list to used them how I needed
OTHER TIPS
This post might help. It gives a solution using a custom ResourceCursorAdapter
, which provides a CheckBox
and a TextView
for each ListView
row.
To select multiple items in ListView
, check this page. Note that the example uses a ListActivity
instead of a ListFragment
, but your code will end up being extremely similar. Just make sure you implement the Fragment
lifecycle methods correctly (i.e. setting the Adapter in the ListFragment
's onActivityCreated()
, etc.).