改变一个项目的背景色的Andr​​oid ListActivity onListItemClick [英] Change background color of an item in Android ListActivity onListItemClick

查看:211
本文介绍了改变一个项目的背景色的Andr​​oid ListActivity onListItemClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这听起​​来很简单,大概有这个问题。但没有它可以解决我的问题。所以在这里我们去:

I know it sounds very simple, and there are questions about this. But none of it could solve my problem. So here we go:

我想换一个列表项的背景颜色在 ListActivity 当用户点击它,当用户再次点击将其改回原来的颜色(即选择/取消选择的项目排序的样子)

I want to change background color of a list item in a ListActivity when user clicks on it, and change it back to original color when user clicks again (i.e. Select/Unselect item sort of look)

我尝试使用getChildAt,它完美的作品,如果我有在同一个屏幕上可见的物品,而无需滚动。

I tried using getChildAt, it works perfectly if I have all the items visible in one screen without having to scroll.

code:

getListView().getChildAt(position).setBackgroundColor(Color.CYAN);

这个问题开始时,我有更多的项目在列表中,用户必须滚动查看。一旦背景项被改变时,背景颜色显示出来的新的可见项目,如我滚动。此外, getChildAt(位置)返回(因此一个 NullPointerException异常)的项目再次点击时。

The problem begins when I have more items in the list and user has to scroll through them. Once background for an item is changed, The background color shows up on the newly visible items as I scroll. Also, the getChildAt(position) returns null (and hence a NullPointerException) when clicking again on the item.

任何人都可以请帮我用一个简单的code,可以帮助我改变列表项的背景颜色?

Can anyone please help me with a simple code that helps me change background color of a list item?

在此先感谢!

推荐答案

当然可以。我将在做一个自定义的getView()方法 ListAdapter

Sure thing. I would do this in the getView() method of a custom ListAdapter.

MyAdapter extends SimpleAdapter {
    private ArrayList<Integer> coloredItems = new ArrayList<Integer>();

    public MyAdapter(...) {
        super(...);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);

        if (coloredItems.contains(position)) {
            v.setBackgroundColor(Color.CYAN);
        } else {
            v.setBackgroundColor(Color.BLACK); //or whatever was original
        }

        return v;
    }
}

更新 coloredItems 列表项被点击时。

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    if (coloredItems.contains(position)) {
        //remove position from coloredItems
        v.setBackgroundColor(Color.BLACK); //or whatever was original
    } else {
        //add position to coloredItems
        v.setBackgroundColor(Color.CYAN);
    }
}

这篇关于改变一个项目的背景色的Andr​​oid ListActivity onListItemClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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