简体   繁体   English

如何在列表视图中设置项目的背景色

[英]How to set the background color of an item in a list view

I have a list view full of items that contain multiple widgets each such as imageviews and checkboxes. 我有一个充满所有包含多个小部件(例如imageviews和复选框)的项目的列表视图。 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. 我做了一些研究,我意识到重用和良好优化是listview的功能,因此选中的复选框被重用了。 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. 到目前为止,我已经在视图线性布局上尝试了setbackgroundcolor和setimagebitmap,并且都具有上述结果。

Thank you 谢谢

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. 另外,每次将数据项绑定到视图时,都应基于此字段值设置复选框。

If you used adapter class. 如果使用适配器类。 Then you can add onItemClickListner in getView brackets. 然后,您可以在getView括号中添加onItemClickListner。 Is available in adapter class. 在适配器类中可用。 And using View object and item position set color for that. 并使用View对象和项目位置为其设置颜色。

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. 保存位置和状态,然后在适配器中根据位置的阵列项设置视图状态。

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

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