解决RecycleView中ViewHolder复用导致图片信息错乱的现象

方法1:使用setTag进行对图片进行标记

public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
        final Note note=notes.get(position);
        final String url=notes.get(position).getPhotoFilePath();
        viewHolder.ivPhoto.setTag(url);     //对ImageView进行标记

        viewHolder.tvId.setText(note.getId() + "");
        viewHolder.tvTitle.setText(note.getTitle());
        viewHolder.tvContent.setText(note.getContent());
        viewHolder.tvTime.setText(note.getTime());
        if (mEditMode == MYLIVE_MODE_CHECK) {
            viewHolder.ivChoiceBox.setVisibility(View.GONE);
        } else {
            viewHolder.ivChoiceBox.setVisibility(View.VISIBLE);

            if (note.getIsChoice()==1) {
                viewHolder.ivChoiceBox.setImageResource(R.drawable.ic_choice);
            } else {
                viewHolder.ivChoiceBox.setImageResource(R.drawable.ic_not_choice);
            }
        }

        final Handler handler = new Handler(){

            public void handleMessage(Message msg){
                switch (msg.what){
                    case 1:
                        //Log.i("TAG","handle message");
                        //从缓存中取出
                        //String photoPath=notes.get(position).getPhotoFilePath();
                        if(note.getPhotoFilePath()!=null){
                            String Classname=note.getClassName();
                            String compressFilePath=note.getPhotoFilePath().replaceAll(Classname,"Compress"+Classname);
                            if(compressFilePath!=null){
                                Bitmap bitmap;
                                bitmap=getBitmapFromMemoryCache(compressFilePath);
                                if(bitmap!=null){
                                    if(url.equals(viewHolder.ivPhoto.getTag())){    //判断标记是否相同
                                        viewHolder.ivPhoto.setImageBitmap(bitmap);
                                        Log.d("是否是从缓存中获取",position+" "+"是");
                                    }
                                }else{
                                    if(url.equals(viewHolder.ivPhoto.getTag())){
                                        bitmap=getBitmap(compressFilePath);
                                        viewHolder.ivPhoto.setImageBitmap(bitmap);
                                        Log.d("是否是从缓存中获取",position+" "+"不是");
                                    }
                                }
                            }else{
                                viewHolder.ivPhoto.setVisibility(View.GONE);
                            }
                        }
                }
            }
        };

方法2:在活动中获取RecycleView实例后,使用

recycleView.setItemViewCacheSize(int); //设置缓存viewholder的个数,防止图片错乱

这里是借鉴:https://blog.csdn.net/MeloDev/article/details/76691951
这位老哥的

如果上面两种方法都解决不了,就只能使用方法3:
方法3:两者综合。

你可能感兴趣的:(Java,安卓开发)