Because in Adapter, ViewHolder is cached for performance to prevent ListView and RecyclerView from creating too many itemViews and consuming too much performance.
Let's briefly talk about ListView and BaseAdapter. The code is very simple:
@Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null){ holder = new ViewHolder(); 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){//When the position is divisible by 3, change its background color holder.button.setBackgroundColor(Color.BLUE); } return convertView; }
Normal situation, as shown below
When we swipe a few more times
There will be a dislocation as shown in the figure above, and the solution is very simple
if (position % 3 == 0){ holder.button.setBackgroundColor(Color.BLUE); }else { holder.button.setBackgroundColor(Color.GRAY); }
Reset the background of each holder to prevent the item from using the background of the item in the cache