`package com.truuce.anotherrvtest
import android.media.Image
data class Item (
val title:String,
val image: Int
) // I can change image type to Drawable to get .setImageDrawable to be accepted by IDE but then the "R.drawable.ashbringer" all need to be changed to something else`
`package com.truuce.anotherrvtest
object ItemList {
val itemList = listOf<Item>(
Item("Ashbringer", R.drawable.ashbringer),
Item("Citadel", R.drawable.ashbringer),
Item("Stonewall", R.drawable.ashbringer),
Item("Tainted Blade", R.drawable.ashbringer)
)
}
// these are of type Int so they do not work when image is set to Drawable`
`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
itemBinding.image.setImageDrawable(item.image) // what do I need here??
}
}
}`
我已经尝试改变val image: Int类型drawable代替,但然后我必须改变" r.d drawable.ashbringer"去别的地方,但我不知道是什么。
我相信这对你来说很容易解决,但是我被难住了。
使用setImageResource
代替,它接受一个整数作为可绘制的资源id
进一步,你可以把你的image
变量标记为@DrawableRes
,以确定它是一个可绘制的资源,而不是一个普通的整数。
使用ContextCompat要先获得drawable,然后尝试设置它
这里有一个类似的问题
我明白了…只需要使用. setimageresource()。这适用于r .drawable.ashbring
`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
itemBinding.image.setImageResource(item.image) //here
}
}
}`