Home > Back-end >  How to change certain item's properties in recyclerview
How to change certain item's properties in recyclerview

Time:01-27

I want to change the background color of an imageview when I click on it, I'm facing a problem with changing the properties of item's position which is int, because position is int, I can't access it's properties, here is my code:

package com.example.myapplication.recyclerView.otherCategoryIcon

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.R
import com.example.myapplication.icons


class OtherCategoryIcon(): RecyclerView.Adapter<OtherCategoryIcon.ItemViewHolder>() {
    val list = icons
    class ItemViewHolder(view: View): RecyclerView.ViewHolder(view) {
        val icon: (ImageView) = view.findViewById(R.id.icon)
    }


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

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = list[position]
        holder.icon.setImageResource(item)
        holder.icon.setOnClickListener {
            holder.icon.background = holder.itemView.context.resources.getDrawable(R.color.blue_400, null)
            holder.icon.background.alpha = 75
            val lastPosition = holder.adapterPosition - 1
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val adapter = LayoutInflater.from(parent.context).inflate(R.layout.icons_layout, parent, false)
        return ItemViewHolder(adapter)
    }
}

how can I change it?

CodePudding user response:

try this:

class OtherCategoryIcon(): RecyclerView.Adapter<OtherCategoryIcon.ItemViewHolder>() {
    
    var lastViewHolder: ItemViewHolder? = null
    val list = icons


    class ItemViewHolder(view: View): RecyclerView.ViewHolder(view) {
        val icon: (ImageView) = view.findViewById(R.id.icon)
    }


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

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = list[position]
        holder.icon.setImageResource(item)
        holder.icon.setOnClickListener {
            holder.icon.background = holder.itemView.context.resources.getDrawable(R.color.blue_400, null)
            holder.icon.background.alpha = 75

            // last click viewholder
            lastViewHolder?.let {
                it.icon.background = it.itemView.context.resources.getDrawable(R.color.blue_400, null)
                it.icon.background.alpha = 1.0
            }
            lastViewHolder = holder
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val adapter = LayoutInflater.from(parent.context).inflate(R.layout.icons_layout, parent, false)
        return ItemViewHolder(adapter)
    }
}
  •  Tags:  
  • Related