Home > Software design >  Android recycler view update
Android recycler view update

Time:11-09

I have a recycler view with a delete button for every item,and the data for the recycler view is a Live Data list.

Basically im observing the list and when i delete an item i just pass the adapter again to the recycler view with the new list in order for the list to update,like this

viewModel.loadBasketItems().observe(viewLifecycleOwner, {
            adapter = BasketFragmentAdapter(it, viewModel, requireContext())
            recycler.adapter = adapter
        }) 

My first problem with this is that the image jumps to the top of the list every time i delete an item,because the list is created again completely

My second problem with this is i don't think this is very efficient.

What's the best method to update the recycler view after you change something

CodePudding user response:

You shouldn't be resetting the adaptor like that. Keep the adaptor the same, but call notifyDataSetChanged(). This tells the adaptor its data has changed, which will tell the recycler view to redraw itself. What you're doing makes the recycler view assume it has a whole new adaptor and needs to drop all info about the old one.

Even better would be to call one of the more specific notify functions on the adapter that tell it what elements changed, but the general one is good enough until you see perf issues.

  • Related