Android中 ListView,RecyclerView中item显示错位的问题?

因为在Adapter中,为了性能都会给ViewHolder做缓存,防止ListView,RecyclerView创建过多的itemView,消耗过多的性能

下面就以ListView和BaseAdapter简单地讲一下,代码很简单:

@Override

publicViewgetView(intposition, View convertView, ViewGroup parent){

ViewHolder holder =null;

if(convertView ==null){

holder =newViewHolder();

convertView = layoutInflater.inflate(R.layout.item,null);

            holder.button = convertView.findViewById(R.id.button);

            convertView.setTag(holder);

}else{

            holder = (ViewHolder) convertView.getTag();

        }

holder.button.setText(""+position);

if(position %3==0){//当position能被3整除时,就改变其背景颜色

            holder.button.setBackgroundColor(Color.BLUE);

        }

returnconvertView;

    }

``

正常情况,如下图

![image](http://upload-images.jianshu.io/upload_images/6095830-95e6c1f34c039b16?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

当我们多滑动几次后

![image](http://upload-images.jianshu.io/upload_images/6095830-f6a137f20f07d3d5?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

就会出现如上图的错位情况,解决办法也很简单

if(position %3==0){

        holder.button.setBackgroundColor(Color.BLUE);

}else{

        holder.button.setBackgroundColor(Color.GRAY);

    }
对每个holder的背景都重新设置一次,防止item使用缓存中item的背景

你可能感兴趣的:(Android中 ListView,RecyclerView中item显示错位的问题?)