简体   繁体   English

备用颜色在动态列表视图中滚动期间更改其位置

[英]Alternate color changes its position during scrolling in dynamic listview

if (convertView == null) {
            vh = new ViewHolder();
            convertView = inflater.inflate(R.layout.search_dtl_grid, parent, false);

        //  vh.llMain = (LinearLayout) convertView.findViewById(R.id.sdg_ll_main);
            if (pos % 2 == 0) {
                convertView.setBackgroundColor(Color.parseColor("#A4A4A4"));
            } else{
                convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));
            }

I have tried the above code in adapter The list is coming with alternate color but when we scroll down the color changes its position like first they are coming grey white grey white but after scrolling it up or down it comes grey grey white grey white white like that , i have searched this many solution are given in that they are saying to add else part for second color i have already done that but still no success.我已经在适配器中尝试了上面的代码列表带有替代颜色但是当我们向下滚动时颜色会改变它的位置就像首先它们是灰白色灰白色但是在向上或向下滚动它之后它变成灰色灰色白色灰色白色白色那,我已经搜索了很多解决方案,因为他们说要为第二种颜色添加其他部分,我已经这样做了,但仍然没有成功。 Please provide me wih a good solution.请为我提供一个好的解决方案。 thanks谢谢

When you use the ViewHolder pattern in a ListView (something that you should do) you have to understand it first.当您在ListView使用ViewHolder模式时(您应该这样做),您必须首先了解它。

Android reuses the views you have already inflated. Android 重用您已经膨胀的视图。 So you have to distinguish two scenarios:所以你必须区分两种情况:

  • The view you are using is not inflated您正在使用的视图没有膨胀
  • The view you are using is some one you already inflated and is being reused您正在使用的视图是您已经膨胀并正在重用的视图

In the first case you have to inflate the view, create a ViewHolder and set it as the view's tag.在第一种情况下,您必须膨胀视图,创建一个ViewHolder并将其设置为视图的标记。

In the second case the only thing you have to do is recover the ViewHolder object.在第二种情况下,您唯一需要做的就是恢复ViewHolder对象。

After that, work with the ViewHolder .之后,使用ViewHolder Take a look at this example .看看这个例子

In your concrete case, the solution will be something like:在您的具体情况下,解决方案将类似于:

if (convertView == null) {
    inflateView(...);
    createViewHolder(...);
} else {
    recoverViewHolder(...);
}

if (pos % 2 == 0) {
    convertView.setBackgroundColor(Color.parseColor("#A4A4A4"));
} else{
    convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));
}

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

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