kotlin 尝试将图像添加到回收程序视图,无法指定可绘制

kpbwa7wx  于 2023-01-05  发布在  Kotlin
关注(0)|答案(3)|浏览(97)
`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图像:Int改为输入drawable,但之后我必须将"R. drawable. ashbringer"更改为其他内容,但idk是什么。
我相信这对你们来说很容易解决,但我被难住了。

ejk8hzay

ejk8hzay1#

使用setImageResource代替,它接受整数作为可绘制资源id
此外,您可以将image变量标记为@DrawableRes,以将其标识为可绘制资源,而不是普通整数。

vkc1a9a2

vkc1a9a22#

首先使用ContextCompat获取可绘制对象,然后尝试设置它
这是一个similar question

laawzig2

laawzig23#

我想通了。。只需要使用。setimagesource()。这适用于R。drawable。ashbringer

`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
        }
    }

 
}`

相关问题