[英]Checkbox issue in custom listview
I want to select all CheckBox from Custom ListView on single Button click . 我想从“单击单个按钮”的“ 自定义ListView”中选择所有CheckBox 。
But when I have more than 9 items in ListView I am getting NullPointerException in below second line of code. 但是,当ListView中有9个以上的项时,我在第二行代码下面得到了NullPointerException。
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. 您弄错了, ListView
重用了您的行,这意味着在内存中创建的行/布局的数量不等于数组中的项。
Typically ListView
re-sets the new data to previous row upon scroll. 通常, ListView
在滚动时会将新数据ListView
为上一行。
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. 我建议您研究此博客文章 ,作者在这里保持Checked状态,然后在适配器的getView()
进行相应设置。
The author have created an array of bolean like this: 作者创建了如下数组的bolean:
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. 并存储选中或取消选中状态,然后从getView()
访问它,您将要做的是,将为所有索引存储true
并刷新适配器。 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. 为了您的方便, ListView
拥有一个BooleanSparseArray
来存储要检查的项目。 This array contains a map of item id (index/position of items in adapter) to a boolean value. 此数组包含项ID(适配器中项的索引/位置)到布尔值的映射。
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. 由于ListView
会为您完成所有操作,因此避免重新发明轮子并使用ListView
的功能来保持其项目的选中状态非常有好处。 All you have to do is to set a choice mode for ListView
: setChoiceMode(int choiceMode)
您要做的就是为ListView
设置选择模式: setChoiceMode(int choiceMode)
To get any item's state, call isItemChecked(int position)
on ListView
. 要获取任何项目的状态,请在ListView
上调用isItemChecked(int position)
。 Useful, if you are overriding getView()
of adapter. 如果您要覆盖适配器的getView()
,则很有用。
To get all what's checked, call getCheckedItemPositions()
on ListView
. 要获取所有已检查的内容,请在ListView
上调用getCheckedItemPositions()
。
To set checked value, call setItemChecked(int position, boolean value)
on ListView
. 要设置检查值,请在ListView
上调用setItemChecked(int position, boolean value)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.