I want to select all CheckBox from Custom ListView on single Button click .
But when I have more than 9 items in ListView I am getting NullPointerException in below second line of code.
View vi= diffeneceLv.getChildAt(i);
CheckBox cb = (CheckBox) vi.findViewById(R.id.conschkbx);
You are getting it wrong, ListView
re-uses your rows, which means number of created rows/layouts in memory are not equal to your items in array.
Typically ListView
re-sets the new data to previous row upon scroll.
I would suggest you to study this blog post , here the author is maintaing the Checked state and then setting it accordingly in getView()
of adapter.
The author have created an array of bolean like this:
private boolean[] thumbnailsselection;
and storing the state of check or uncheck, and later accessing it from getView()
, what you will do is, you will store true
for all index and refresh your adapter. It'll select all your rows.
Here is another post .
You should NOT hold references of individual views for this purpose, as they are recycled.
For your convenience, ListView
holds a BooleanSparseArray
to store what items are checked. This array contains a map of item id (index/position of items in adapter) to a boolean value.
Since ListView
does all that for you, its good to avoid re-inventing the wheel and use ListView
's capability to hold checked state of its items. All you have to do is to set a choice mode for ListView
: setChoiceMode(int choiceMode)
To get any item's state, call isItemChecked(int position)
on ListView
. Useful, if you are overriding getView()
of adapter.
To get all what's checked, call getCheckedItemPositions()
on ListView
.
To set checked value, call setItemChecked(int position, boolean value)
on ListView
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.