简体   繁体   English

自定义列表视图中的复选框问题

[英]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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM