RecyclerView添加图片遇阻:Drawable与资源ID适配问题求助
解决方案:RecyclerView中图片资源ID与Drawable适配问题
方案一:保留Item的image为Int类型(推荐)
不需要修改Item类和ItemList,直接在Adapter的bindItem方法里调整图片设置逻辑即可:
修改后的Adapter代码
package com.truuce.anotherrvtest import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.truuce.anotherrvtest.databinding.RecyclerItemBinding class ItemAdapter:RecyclerView.Adapter<ItemAdapter.MainViewHolder>() { inner class MainViewHolder(val itemBinding: RecyclerItemBinding) : RecyclerView.ViewHolder(itemBinding.root) { fun bindItem(item: Item){ itemBinding.itemNameTV.text = item.title // 方法1:直接用setImageResource传入资源ID(最简便) itemBinding.image.setImageResource(item.image) // 方法2:通过Context获取Drawable后设置(适合需要对Drawable做额外处理的场景) // val drawable = itemView.context.getDrawable(item.image) // itemBinding.image.setImageDrawable(drawable) } } }
方案二:将Item的image改为Drawable类型
如果一定要把Item的image字段改成Drawable类型,需要在创建Item实例时通过Context将资源ID转换为Drawable对象:
修改后的Item类
package com.truuce.anotherrvtest import android.graphics.drawable.Drawable data class Item ( val title:String, val image: Drawable )
修改后的ItemList(需传入Context)
package com.truuce.anotherrvtest import android.content.Context object ItemList { // 传入Context来将资源ID转为Drawable fun getItems(context: Context) = listOf<Item>( Item("Ashbringer", context.getDrawable(R.drawable.ashbringer)!!), Item("Citadel", context.getDrawable(R.drawable.ashbringer)!!), Item("Stonewall", context.getDrawable(R.drawable.ashbringer)!!), Item("Tainted Blade", context.getDrawable(R.drawable.ashbringer)!!) ) }
对应Adapter的bindItem方法(无需修改)
fun bindItem(item: Item){ itemBinding.itemNameTV.text = item.title itemBinding.image.setImageDrawable(item.image) }
注意:
getDrawable()可能返回null,所以用!!强制非空,也可以根据需求做空判断;如果要避免多个Item共享同一Drawable状态,可调用drawable.mutate()创建副本。
内容的提问来源于stack exchange,提问作者Truuce
相关产品推荐
相关产品推荐

