Should we use RecyclerView to replace ListView? [closed]
Android Docs say:
The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events
Actually ListView
can do all of the above if efficiency doesn't matter, and we have found many issues when we use RecyclerView
to replace ListView
:
There is no onItemClickListener() for list item selection - solution
No divider between list items - solution
No built-in overlap selector, there is no visual feedback when you click list item - solution
No addHeaderView for list header - solution
Maybe more issues ...
So when we use RecyclerView
to replace ListView
, we have to do much extra coding to reach the same effect as ListView
.
QUESTION:
- Is it worth that we replace
ListView
withRecyclerView
totally ?- if not then in which case should we better use
RecyclerView
insteadListView
, and vice versa ?
Solution 1:
If ListView works for you, there is no reason to migrate. If you are writing a new UI, you might be better off with RecyclerView.
RecyclerView is powerful when you need to customize your list or you want better animations. Those convenience methods in ListView caused a lot of trouble to people which is why RecyclerView provides a more flexible solution to them.
The major change you need to make for migration is in your adapter. If you want to keep calling notifyDataSetChanged
, you lose most of the animation & binding benefits. But if you can change your adapter to dispatch detailed notify events (added/removed/moved/updated), then you get much better animations and performance. These events let RecyclerView choose correct animations and it also helps it avoid unnecessary onBind
calls. You'll get a huge benefit if your item views are complex. Also, going forward, there will be more components around RecyclerView.
Solution 2:
1 You can use an interface to provide a click listener. I use this technique with ListViews, too.
2 No divider: Simply add in your row a View with a width of match_parent and a height of 1dp and give it a background color.
3 Simply use a StateList selector for the row background.
4 addHeaderView can be avoided in ListViews, too: simply put the Header outside the View.
So, if efficiency is your concern, then yes, it's a good idea to replace a ListView with a RecyclerView.