简体   繁体   English

ListView项目背景色

[英]ListView item background color

I have a ListView in which every second item should have a different color (for example: white -> gray -> white ->gray etc.), it seems to work initially but as soon as I start scrolling, the rendering of the backgroundcolor seems to fail: the other color is set randomly to the items, also when I scroll up again this happens to the items where the color was correct at the beginning. 我有一个ListView,其中每个第二个项目都应具有不同的颜色(例如:白色->灰色->白色->灰色等),它最初似乎可以正常工作,但是一旦我开始滚动,就会显示backgroundcolor似乎失败了:另一种颜色随机设置到项目上,当我再次向上滚动时,这也会发生在开始时颜色正确的项目上。 Can someone hint me why this is happening? 有人可以提示我为什么会这样吗?

I have tried this in the Adapter: 我已经在适配器中尝试过此操作:

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

and this in my ListFragment: 这在我的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));
        }
    }   
};

UPDATE: 更新:

I have done a bit of logging and found out that, if I am adding more elements than visible on the screen and check for the ListViews child count, the ListView only holds the children which are initially visible to the screen, the rest seems to be loaded/added when scrolling is done. 我做了一些日志记录后发现,如果我添加的元素多于屏幕上可见的元素,并检查ListViews子级计数,则ListView仅保存最初在屏幕上可见的子级,其余似乎是滚动完成后加载/添加。

in your adapter use this code.. its work.. u need to provide else condition. 在您的适配器中使用此代码..其工作..您需要提供else条件。

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

在此处输入图片说明

Try this in your Adapter's getView() 在适配器的getView()中尝试一下

if((position % 2) == 1) {
                  LayoutHolder.setBackgroundColor(getContext().getResources().getColor(R.color.white));
}else{
            LayoutHolder.setBackgroundColor(getContext().getResources().getColor(R.color.gray)
}

尝试在onPostExecute()中添加它

getListView().getChildAt(i).setCacheColorHint(getSherlockActivity().getResources().getColor(R.color.light_green));

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

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