0

I have a RecyclerView and every list item has a ChipGroup in it. I want to inflate Chips from xml and add them to the ChipGroup. Every list item has 1 to 4 chips. If my RecyclerView has 50 items, Chips get inflated 50 to 200 times. Thanks to the ViewHolder pattern, RecyclerView items get inflated only once. It should be possible to reduce the inflation count to at most 50 for Chips. How can I apply same ViewHolder pattern for Chips?

osrl
  • 8,168
  • 8
  • 36
  • 57

3 Answers3

1

If each element in the RecyclerView has 1-4 chips in it, I think it would be totally reasonable to just always inflate four chips, but dynamically show/hide them when you bind the ViewHolder. If you had huge numbers of chips, this strategy might not be ideal, but for four it should be fine.

Ben P.
  • 52,661
  • 6
  • 95
  • 123
0

If I understood correctly, you are concerned about performance of RecyclerView. You are not showing your code nor providing screenshots, so I assume you have something like 5 to 8 items on screen and 50 of them in total. As everybody knows, RecyclerView introduced by Google to do exactly that - handle performance issues of large lists. Once item is no longer visible on screen be sure that RecyclerView... recycles it (read: removes it from memory). So in your case, only from 5 to 24 chips per screen - not that big of a deal. And IMHO there is no better way of handling inflation and recycling views by ourselves better than RecyclerView does it. Google guys made it very robust and in clever way.

Roman T.
  • 333
  • 3
  • 10
-1

The ViewHolder pattern re-uses each view declared in a ViewGroup. You are adding Chips dynamically to your ChipGroup (and hence your ViewGroup) on a per item basis; the RecyclerView has no way of knowing which Chips you want to reuse.

You could create 50 placeholder chips in your ChipGroup layout in XML and then dynamically update/show/hide them, but this is not a very elegant solution.

urgentx
  • 3,832
  • 2
  • 19
  • 30
  • Any recommendations on a more “elegant” way to handle a larger number of chips? – Bink Jan 22 '19 at 21:49
  • You could pass in a list of 50 programmatically created chips to the constructor of your ViewHolder in `onCreateViewHolder()`, where you'd add them to the layout. Then you can iterate through them in `onBindViewHolder()` and set their visibility/content. – urgentx Jan 23 '19 at 14:52