我想在单击 Button 时从Custom ListView中选择所有CheckBox 。
但是当我在 ListView 中有超过 9 个项目时,我在第二行代码下面得到 NullPointerException。
View vi= diffeneceLv.getChildAt(i);
CheckBox cb = (CheckBox) vi.findViewById(R.id.conschkbx);
我想在单击 Button 时从Custom ListView中选择所有CheckBox 。
但是当我在 ListView 中有超过 9 个项目时,我在第二行代码下面得到 NullPointerException。
View vi= diffeneceLv.getChildAt(i);
CheckBox cb = (CheckBox) vi.findViewById(R.id.conschkbx);
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
.