androidkotlinandroid-recyclerviewnestedrecyclerview

How to use nested Recyclerview in Android


In my application I want use RecyclerView into another Recyclerview and for this I wrote below codes.

But after run application messed colors when scroll on items!

I have one RecyclerView for show products and into this RecyclerView I have onother RecyclerView for show colors!

How can I fix this problem?


Solution

  • Each colour ViewHolder has its own RecyclerView, right? It needs its own ColorsAdapter too - that's what you're using to tell a specific RecyclerView to display a specific set of colours.

    Right now you have one adapter that you're reusing in all your RecyclerViews:

    // top-level in SearchAdapter
    lateinit var colorsAdapter: ColorsAdapter
    
    // when binding a ViewHolder
    colorsAdapter.setData(colors)
    binding.itemsColors.setupRecyclerview(
        LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, true),
        colorsAdapter
    )
    

    So any change you make to that single adapter will update every RecyclerView that's using it. And in that bind function, you call setData(colors) on that single adapter - you're basically updating everything to display those same colours.


    Just like each ViewHolder has its own RecyclerView in the layout, you need it to have its own ColorsAdapter too. So you can just create one when each ViewHolder instance is created:

    
    inner class ViewHolder(
        private val binding: ItemSearchListBinding
    ) : RecyclerView.ViewHolder(binding.root) {
    
        // create a unique instance for this VH to use
        private val colorsAdapter = ColorsAdapter()
    
        ...
    }
            
    

    And now your bind function will refer to the VH's specific instance of the adapter (don't forget to delete the top-level one in SearchAdapter since you're not using it now). Also you'll have to work out how to make this work with whatever dependency injection you're doing.