Home > front end >  Trying to add images to my recycler view, can't assign drawable
Trying to add images to my recycler view, can't assign drawable

Time:01-04

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

 
}`

I've tried changing the val image: Int to type drawable instead, but then I have to change the "R.drawable.ashbringer" to something else, but idk what.

I'm sure this is an easy fix for ya'll on here, but I'm stumped.

CodePudding user response:

Use setImageResource instead, it accepts an integer as the drawable resource id

Further more you can mark your image variable as @DrawableRes to identify it as an drawable resource, not a normal integer.

CodePudding user response:

Use ContextCompat to get the drawable first, then try setting it

Here is a similar question

CodePudding user response:

I figured it out.. just needed to use .setImageResource(). This works with 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
        }
    }

 
}`
  • Related