Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change Recyclerview background with click in Android

In my application I want used RecyclerView and I want when click on Items, change background.
I want first show default item for selected and when user change this default item, change background and deselected this default item.

My Code :

class StateAdapter constructor() : RecyclerView.Adapter<StateAdapter.ViewHolder>() {

    private lateinit var binding: ItemSimpleTxtBinding
    private lateinit var context: Context
    private var moviesList = emptyList<StateTypes>()
    private var selectedItem = -1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        binding = ItemSimpleTxtBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        context = parent.context
        return ViewHolder()
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        //getItem from PagingDataAdapter
        holder.bind(moviesList[position], position)
        //Not duplicate items
        holder.setIsRecyclable(false)
    }

    override fun getItemCount() = moviesList.size

    inner class ViewHolder : RecyclerView.ViewHolder(binding.root) {

        @SuppressLint("SetTextI18n")
        fun bind(item: StateTypes, position: Int) {
            binding.apply {
                itemTxt.text = item.name
                //Click
                binding.itemCard.setOnClickListener {
                    selectedItem = adapterPosition
                    notifyDataSetChanged()
                    onItemClickListener?.let {
                        it(position)
                    }
                }
                //Change color
                if (selectedItem == adapterPosition) {
                    binding.itemCard.setCardBackgroundColor(ContextCompat.getColor(context, R.color.meatBrown))
                } else {
                    binding.itemCard.setCardBackgroundColor(ContextCompat.getColor(context, R.color.white))
                }
                //Default
                selectedItem = 1
            }
        }
    }

    private var onItemClickListener: ((Int) -> Unit)? = null

    fun setOnItemClickListener(listener: (Int) -> Unit) {
        onItemClickListener = listener
    }

    fun setData(data: List<StateTypes>) {
        val moviesDiffUtil = NotesDiffUtils(moviesList, data)
        val diffUtils = DiffUtil.calculateDiff(moviesDiffUtil)
        moviesList = data
        diffUtils.dispatchUpdatesTo(this)
    }

    class NotesDiffUtils(private val oldItem: List<StateTypes>, private val newItem: List<StateTypes>) :
        DiffUtil.Callback() {

        override fun getOldListSize(): Int {
            return oldItem.size
        }

        override fun getNewListSize(): Int {
            return newItem.size
        }

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldItem[oldItemPosition] === newItem[newItemPosition]
        }

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldItem[oldItemPosition] === newItem[newItemPosition]
        }
    }
}

For set default item I added this code :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//Default
selectedItem = 1

But after added this line, when click on Item not change any items background!
When removed default item change items background successfully!
How can I fix it?

>Solution :

You are setting selectedItem = 1 in every cell of the recyclerview. Set selectedItem = 1 once as global variable instead of -1 like this:

 private var selectedItem = 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading