2

我有一个 ListView ,其中每隔一个项目应该有不同的颜色(例如:白色->灰色->白色->灰色等),它最初似乎可以工作,但是一旦我开始滚动,背景色的渲染似乎失败了:另一种颜色是随机设置的,当我再次向上滚动时,这也会发生在开始颜色正确的项目上。有人可以提示我为什么会这样吗?

我在适配器中试过这个:

    if((position % 2) == 1) {
        layoutHolder.setBackgroundColor(getContext().getResources().getColor(R.color.light_green));
    }

这在我的 ListFragment 中:

    private AsyncTask<Void, Void, Void> fillList = new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground(Void... params) {
        addListItems();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        for (int i = 1; i < getListView().getChildCount()-1; i = i+2) {
            LOGI(TAG, "for-loop " + String.valueOf(i));
            getListView().getChildAt(i).setBackgroundColor(getSherlockActivity().getResources().getColor(R.color.light_green));
        }
    }   
};

更新:

我做了一些日志记录并发现,如果我添加的元素多于屏幕上可见的元素并检查 ListViews 子项计数,则 ListView 仅包含最初对屏幕可见的子项,其余的似乎是滚动完成时加载/添加。

4

3 回答 3

4

在您的适配器中使用此代码..它的工作..您需要提供其他条件。

if ( position % 2 == 0 ){
                convertView.setBackgroundColor(Color.GREEN);
            }else{
                convertView.setBackgroundColor(Color.RED);
            }

在此处输入图像描述

于 2013-01-17T12:41:12.200 回答
1

在适配器的 getView() 中试试这个

if((position % 2) == 1) {
                  LayoutHolder.setBackgroundColor(getContext().getResources().getColor(R.color.white));
}else{
            LayoutHolder.setBackgroundColor(getContext().getResources().getColor(R.color.gray)
}
于 2013-01-17T12:21:19.273 回答
0

尝试在 onPostExecute() 中添加它

getListView().getChildAt(i).setCacheColorHint(getSherlockActivity().getResources().getColor(R.color.light_green));
于 2013-01-17T12:22:58.087 回答