如何设置列表视图中项目的背景颜色
我有一个充满项目的列表视图,每个项目都包含多个小部件,例如图像视图和复选框。我有一个数组适配器和一个用于搜索功能的过滤器。我遇到的问题是我想选中复选框并发生一些事情。我的测试所做的是选中列表视图顶部项目中的复选框并让它打印出其状态。我注意到这有效,但是当我向下滚动时,其他复选框也被选中。我做了一些研究,我意识到列表视图的一个功能是重用并得到很好的优化,因此选中的复选框被重用。我想知道是否可以让我选中列表中某个项目的复选框,并让相应的项目在滚动时变成一种颜色,而不让其他项目变成相同的颜色。
到目前为止,我已经在视图线性布局上尝试了 setbackgroundcolor 和 setimagebitmap ,并且都具有上述结果。
谢谢
I have a list view full of items that contain multiple widgets each such as imageviews and checkboxes. I have an array adapter and a filter for search functionality. The problem i have is i want to check the check boxes and have something happen. What i did for my test was to check the check box that exists at the top item in the list view and have it print out its state. I noticed that this worked but when i scrolled down , that other check boxes were selected as well. I did some research and i realized that it is a feature of listview to reuse and be well optimized and thus the checked checkbox was being reused. I want to know is it possible to have me check a check box in one of my items in my list, and have the corresponding item turn a color and not have other items turn the same color when i scroll.
So far i have tried setbackgroundcolor and setimagebitmap on the views linear layout, and both have the above results.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,您想要执行此操作的方法是将视图和数据代码更好地分开。您的数据项上应该有一个字段,该字段反映在复选框和/或背景颜色中。这意味着当您选中复选框时,您不应直接更改背景颜色,而应更改基础数据项的值。此外,每次将数据项绑定到视图时,都应该根据此字段值设置复选框。
Really the way you want to do it is to keep your view and data code better separated. You should have a field on your data item that is reflected in the checkbox and/or background color. This means that when you check your checkbox, you shouldn't just change the background color directly, but instead change the value of the underlying data item. Also, every time you bind your data item to your view, you should set the checkbox based on this field value.
您需要的是将复选框状态存储在某种数组中。在其中保存位置和状态,然后在适配器中根据位置中的数组项设置视图状态。
What you need - is to store checkbox state in some sort of array. Save position and state in it, and then in your adapter set view state according to array item in position.
如果您使用适配器类。然后你可以在getView括号中添加onItemClickListner。在适配器类中可用。并使用视图对象和项目位置为其设置颜色。
If you used adapter class. Then you can add onItemClickListner in getView brackets. Is available in adapter class. And using View object and item position set color for that.