androidandroid-recyclerviewhorizontalscrollviewhorizontal-recyclerview

Android Horizontal Recyclerview Shows multiple select on scroll


I need to select the first item as default selection and selecting a single item on click. But when I scroll and see I could see it selected after every 8th item.it even included the margin-left for multiple items, which I only included for the first item in horizontal recyclerview.

companion object {
        private var lastCheckedtab: ConstraintLayout? = null
    }
fun bind(
            context: Context?,
            name: String,
            position: Int
    ) {
        if (position == 0) {
            cardView?.isSelected = true
            cardView?.isClickable = false
            lastCheckedtab = cardView
            val p = cardView?.layoutParams as ViewGroup.MarginLayoutParams?
            p?.leftMargin = 52
        }
        itemView.setOnClickListener{
            val checkedTab = it as ConstraintLayout
            checkedTab.isSelected = true
            checkedTab.isClickable = false
            if (lastCheckedtab != null && lastCheckedtab != checkedTab) {
                lastCheckedtab?.isSelected = false
                lastCheckedtab?.isClickable = true
                context?.let { it1 ->
                    checkedTab.findViewById<TextView>(R.id.iv_tab_name).setTextColor(
                        ContextCompat.getColor(
                            it1,
                            R.color.black
                        )
                    )
                    lastCheckedtab?.findViewById<TextView>(R.id.iv_tab_name)?.setTextColor(
                        ContextCompat.getColor(
                            it1,
                            R.color.setting_text
                        )
                    )
                }
            }
            lastCheckedtab = checkedTab
        }
}        


 override fun onBindViewHolder(holder: MyHolder, position: Int) {
        holder.bind(context, tabs.get(position), position)
    }

Solution

  • That is because you selected the first ViewHolder, but never unselected it.

    RecyclerView (as the name suggests) recycles the ViewHolders instead of always making new ones.

    If you want to only select the first item, then you should have some sort of state saving, to know what items are selected, and have that state start with the first item as selected.

    Then when you bind the ViewHolder, check if the position is selected or not