如何更改 ListView 中所选项目的背景颜色? [英] How to change background color of selected items in ListView?

查看:20
本文介绍了如何更改 ListView 中所选项目的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过许多类似的问题,每个答案都针对问题非常具体,没有直接的答案,或者我找到了一些教程,展示了如何创建在选定项目上选中的复选框.而且我无法理解如何从这些代码中做到这一点.

i've seen many simillar questions and every answer is very specific to the problem and no straight forward answer, or i found tutorials that show how to create a checkbox that's checked on selected items. And i'm having trouble understanding how to do it from those codes.

我正在学习此处的教程,这就是我的代码看起来只是名称不同的原因.

I am following a tutorial found Here, and that's preaty much how my code looks only different names.

我想要一个多选列表视图,当一个项目被选中时,背景颜色会改变以标记我选择的项目.

I Want to have a multipile selection ListView, when an item selected the background color is changed to mark the items i've selected.

也许我可以使用自定义选择器完成此操作?我理解常用的方法是保存 selected 的位置并在 getView 函数中做一些事情.我看到人们创建 ViewHolder,但我真的不明白它与任何事情有什么关系.有人可以帮我吗?

Maybe i can acomplish this using a custom selector? I understood the common way is to save the positions of selected and do something in the getView function. I saw people creating ViewHolder, but i didn't really understand what it has to do with anything. Can someone please help me?

提前致谢,埃里克

推荐答案

好吧,我终于解决了,希望这对某人有所帮助:

Well i finally solved it, hope this helps someone :

我所做的是创建一个 ArrayList 来存储所选项目的所有位置,并在点击时切换背景颜色.

What i did was created an ArrayList<Integer> that stores all the position of selected items, and toggle the background colors on clicks.

在我的适配器中我定义:

In my Adapter i define:

public ArrayList<Integer> selectedIds = new ArrayList<Integer>();

使用以下方法:

    public void toggleSelected(Integer position)
{
    if(selectedIds.contains(position))
    {
        selectedIds.remove(position);


    }
    else
    {
        selectedIds.add(position);
    }
}

从 ArrayList 中添加删除项目

which addes emoves items from the ArrayList

在我的 getView 方法中:

In my getView method :

            if (selectedIds.contains(position)) {
            convertView.setSelected(true);
            convertView.setPressed(true);
            convertView.setBackgroundColor(Color.parseColor("#FF9912"));
        }
        else
        {
            convertView.setSelected(false);
            convertView.setPressed(false);
            convertView.setBackgroundColor(Color.parseColor("#000000"));
        }

这会检查位置是否存储在 ArrayList 中.如果是,则将其绘制为选定的.如果不是,则相反.

This checks if the position is storred in the ArrayList. if it does, paint it as selected. if not, the opposite.

剩下的是 OnItemClick 侦听器,我补充说:

all is left is the OnItemClick listener, i added :

    ((YourAdapter)list.getAdapter()).toggleSelected(new Integer(position));

当 YourAdapter 是 ListView 的适配器时

When YourAdapter is the adapter of your ListView

希望这对任何人都有帮助,因为这是一个通用的答案:)

Hope this helps anyone, as it's a generic answer :)

这篇关于如何更改 ListView 中所选项目的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆