简体   繁体   English

自定义listview适配器行选择

[英]custom listview adapter row selection

I have listview with custom adapter. 我有带有自定义适配器的listview。 In each row i have 2 textviews and a button. 在每一行中,我有2个textviews和一个按钮。 I want when I click on an item to highlight it and to stay highlighted until i click another item. 我想要当我单击一个项目以突出显示它并保持突出显示状态,直到我单击另一个项目。 I tried to do it with list selector but didn't succeed. 我尝试使用列表选择器执行此操作,但未成功。 Then I tried to do it like this: 然后我尝试这样做:

public void onClick(View v) {
    ListView lvItems = context.lvLists;
    for (int i=0; i < lvItems.getChildCount(); i++) 
    {
        lvItems.getChildAt(i).setBackgroundColor(Color.BLACK);        
    }
    v.setBackgroundColor(Color.parseColor("#555555"));

This is the onclick of each row of the listview. 这是列表视图每一行的onclick。 It works but I saw that when I scroll down there are more items selected (which I didn't select). 它可以工作,但是我看到当我向下滚动时,有更多的项目被选中(我没有选择)。 Solution for this? 解决方案呢?

If you want to save some properties of your ListView items you can't rely on Views themselves. 如果要保存ListView项的某些属性,则不能依赖于View本身。 You have to store them in your data so that your Adapter knows which item's state has changed. 您必须将它们存储在数据中,以便适配器知道哪个项目的状态已更改。 See the answer to this question for more details: 有关更多详细信息,请参见此问题的答案:

Android: Spinners within a ListView loose their values when I add dynamically new ListView entries Android:当我动态添加新的ListView条目时,ListView中的微调器失去其值

您应该实现视图持有人模式,然后在您的持有人代码中,可以有一个(布尔值)变量,该变量保存该项目的当前状态(突出显示或未突出显示),并相应地更改背景颜色。

You have plenty of answers here on Stack Overflow. 您在堆栈溢出方面有很多答案。 Try checking this , this and also this . 尝试检查这个这个以及这个

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

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