Android Kotlin RecyclerView点击事件中图片不显示问题求助
RecyclerView展开项图片加载不显示问题
我有一个RecyclerView,点击“更多信息”按钮时列表项会展开。希望点击该按钮时加载并显示图片,但在点击事件监听器中设置图片后,RecyclerView内的图片并未显示。如果在监听器外设置图片可以正常显示,但因为列表数据量大,会触发大量API请求,所以不想用这种方式。相关代码如下:
holder.moreinfo.setOnClickListener { restaurant.expandable = true var url = "http://maps.google.com/maps/api/staticmap?center=" + restaurant.latitude + "," + restaurant.longitude + "&zoom=15&size=200x200&sensor=false" + "&markers=size:mid%7Ccolor:red%7Clabel:C%7C" + restaurant.latitude + "," + restaurant.longitude + "&key=API_KEY" Log.e("url", url) Glide .with(holder.itemView.context) .load(url) .centerCrop() .into(holder.map) notifyItemChanged(position) }
问题原因及解决办法
核心问题
调用notifyItemChanged(position)后,RecyclerView会重新绑定该位置的ViewHolder,这会覆盖你在点击事件里用Glide设置的图片。因为重新绑定时,Adapter的onBindViewHolder里如果没有处理展开状态下的图片加载逻辑,ImageView会回到初始状态。
正确实现步骤
将图片URL存入数据模型
在点击事件中,不仅标记展开状态,还要把生成的地图URL保存到restaurant对象的新增字段中(比如mapUrl: String?):holder.moreinfo.setOnClickListener { restaurant.expandable = true // 生成URL并保存到数据模型 restaurant.mapUrl = "http://maps.google.com/maps/api/staticmap?center=" + restaurant.latitude + "," + restaurant.longitude + "&zoom=15&size=200x200&sensor=false" + "&markers=size:mid%7Ccolor:red%7Clabel:C%7C" + restaurant.latitude + "," + restaurant.longitude + "&key=API_KEY" notifyItemChanged(position) }在onBindViewHolder中处理图片加载
在Adapter的绑定方法里,根据数据模型的状态决定是否加载图片:override fun onBindViewHolder(holder: ViewHolder, position: Int) { val restaurant = dataList[position] // 处理其他UI逻辑... // 控制地图控件的显示/隐藏 holder.map.visibility = if (restaurant.expandable) View.VISIBLE else View.GONE // 展开状态且有URL时加载图片 if (restaurant.expandable && restaurant.mapUrl != null) { Glide.with(holder.itemView.context) .load(restaurant.mapUrl) .centerCrop() .into(holder.map) } else { // 收起时清空图片,避免复用混乱 Glide.with(holder.itemView.context).clear(holder.map) } }可选优化:添加占位与错误处理
给Glide加上占位图和错误图,提升用户体验:Glide.with(holder.itemView.context) .load(restaurant.mapUrl) .centerCrop() .placeholder(R.drawable.map_placeholder) // 加载中占位图 .error(R.drawable.map_error) // 加载失败图 .into(holder.map)
这样既保证了只有用户点击时才触发API请求,又能在RecyclerView复用ViewHolder时正确维护图片状态,不会出现设置后不显示的问题。
内容的提问来源于stack exchange,提问作者Malhar
相关产品推荐
相关产品推荐

