在RecyclerView中滚动后,ImageView失去了位置

问题描述

每次滚动RecyclerView后,图像的位置都会受到干扰。我正在使用Picasso库将图像放入RecyclerViewAdapter中。我已经测试了recyclerView,它工作正常,问题出在 onBindViewHolder 中。

在此VIDEO中,您会看到第一条“ hello”消息消失了,而另一张图像代替了。

override fun onBindViewHolder(holder: ViewHolder,position: Int) {
  val chat: Chat = mChatList[position]

  //image message
    if(chat.getMessage() == "IMAGE" && chat.getUrl() != ""){

        if(chat.getSender() == currentUserID){
            holder.textMessage?.visibility = GONE
            holder.imageMessageOut?.visibility = VISIBLE
            holder.cardViewOut?.visibility = VISIBLE
            Picasso.get().load(chat.getUrl()).into(holder.imageMessageOut)
        }
        else if (chat.getSender() != currentUserID){
            holder.textMessage?.visibility = GONE
            holder.imageMessageIn?.visibility = VISIBLE
            holder.cardViewIn?.visibility = VISIBLE
            Picasso.get().load(chat.getUrl()).into(holder.imageMessageIn)
        }
    }

 //text message
    else {
        holder.textMessage?.text = chat.getMessage()
    }
}

代码用于外发邮件的布局。这是发件人的一面。

        <androidx.cardview.widget.CardView
            android:id="@+id/card_out"
            android:layout_width="190dp"
            android:layout_height="190dp"
            android:visibility="gone"
            app:cardCornerRadius="10dp"
            app:cardElevation="0dp"
            app:cardBackgroundColor="#8DE3E3E3">

        <ImageView
            android:id="@+id/outgoing_image_message_iv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone" />

        </androidx.cardview.widget.CardView>

        <TextView
            android:id="@+id/text_message_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_rounded_rectangle"/>

错误消息不断出现在logcat中。

E/UIFirst: Failed to open /proc/31416/stuck_info,No such file or directory

解决方法

首先:您的上一个问题已关闭,因为“此问题需要调试详细信息”。因此,您已经将代码交换为图像,发布了完全相同的内容,仍然没有调试数据...为什么您认为这个问题也不值得关闭?

您的问题出在Picasso图像加载中-您正在启动它,但是在加载图像之前ViewHolder回收时永远不会取消。了解回收模式的工作原理(重新使用之前夸大的View /布局/行)并实现取消Picasso的请求,如HERE

如果您在XML中切换顺序-CardView首先是图像,第二个是TextView-那么您将同时获得“ hello”文本和加载的图像。因为此View以前是作为图片夸大的,所以Picasso开始加载图片(网络/缓存需要一些时间),然后将其发布到ImageView(自动进行visibility更改) ,它在设置图像时属于另一个位置的另一条消息-View在另一个位置被回收并重新使用

,

之所以会出现此问题,是因为您没有取消Picasso的请求,因此每当滚动RecyclerView时,图像就会开始加载,并且它们对图像的请求会感到困惑并开始出现在{ {1}},因此您只需要在这种情况的else块中取消请求

ImageView

现在您将看到Picasso.get().cancelRequest(imageMessageOut) 为空,但是因为在图像消息ImageView和ImageView的可见性设置为可见/ em>,因此您会在邮件位置看到空白的CardView。因此,您必须隐藏CardViewImageView或仅隐藏CardView,因为它是CardView的父布局,因此只需将其可见性设置为GONE即可这样的图像信息块

ImageView

不要忘记将cardViewOut?.visibility = GONE 的可见性设置为VISIBLE,因为它在if块中已设置为GONE

textMessage