Home > Net >  How can I use setImageResource (or setImageDrawable) in onBindViewHolder?
How can I use setImageResource (or setImageDrawable) in onBindViewHolder?

Time:06-08

I can't manage to uset setImageResource on my holder (which is a part of a CardView). I've already tried to add a image asset but it didn't seem to work. I would like to know how can I change an image properly in this case.

setImageResource doesn't working

This is the code of the entire page:

package com.example.revenuer.adapter

import android.R
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.revenuer.entity.Operation
import com.example.revenuer.listener.OperationListener


class HistoryAdapter(val list: List<Operation>): RecyclerView.Adapter<HistoryAdapter.OperationViewHolder>() {
    private var listener: OperationListener? = null

    fun setOnOperationListener(listener: OperationListener){
        this.listener = listener;
    }

    class OperationViewHolder(view: View, private val listener: OperationListener?):  RecyclerView.ViewHolder(view){
        val nameView: TextView
        val valueView: TextView
        val dateView: TextView
        val imageView: ImageView
        init {
            view.setOnClickListener{
                listener?.onListItemClick(view, adapterPosition)
            }
            nameView = view.findViewById(com.example.revenuer.R.id.item_cardview_name)
            valueView = view.findViewById(com.example.revenuer.R.id.item_cardview_value)
            dateView = view.findViewById(com.example.revenuer.R.id.item_cardview_date)
            imageView = view.findViewById(com.example.revenuer.R.id.operation_image)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OperationViewHolder{
        val view = LayoutInflater.from(parent.context).inflate(com.example.revenuer.R.layout.operation_item, parent,false)
        return OperationViewHolder(view, listener)
    }

    override fun onBindViewHolder(holder: OperationViewHolder, position: Int) {
        val operation = list[position]
        holder.nameView.text = operation.name
        holder.valueView.text = operation.value
        holder.dateView.text = operation.date
        if (operation.type) {
            holder.imageView.setImageResource(R.drawable.custom_arrow_up)
        }

    }

    override fun getItemCount(): Int {
        return list.size
    }
}

CodePudding user response:

You have import android.R, so in the rest of your code you need to write com.example.revenuer.R to refer to your own package's R, just like you did elsewhere.

Solution:

Replace import android.R with import com.example.revenuer.R and you can replace all com.example.revenuer.R with R. Explicitly write android.R when you need to.

  • Related