1

There are tons of tutorials on how to get a simple RecyclerView going, but now my ViewHolder logic becomes less and less simple. Ideally I would have one instance of MyItemViewModel per ViewHolder, so I can separate UI related helpers. Is this at all possible?

I tried inflating and passing a binding like this:

(in RecyclerView.Adapter.onCreateViewHolder)

val binding = MyViewBinding.inflate(
  LayoutInflater.from(parent.context), parent, false)
return MyViewHolder(binding)

But when I access binding.viewModel in MyViewHolder.setItem(item: Item) called via RecyclerView.Adapter.onBindViewHolder later, it is always null.

Any help? Can/should I instatiate one Fragment(Activity) per Item/ViewHolder so I can use ViewModelProviders? Is there sth similar to ViewModel that I should rather use?

Ümañg ßürmån
  • 9,695
  • 4
  • 24
  • 41
Jasper
  • 1,971
  • 19
  • 34
  • 1
    Its possible to create a RecyclerView with multiple ViewHolder . This might help you https://stackoverflow.com/questions/26245139/how-to-create-recyclerview-with-multiple-view-type/51153083#51153083 – Rohit Singh Nov 19 '18 at 09:10
  • this might help https://android.jlelse.eu/dealing-with-asynchronous-data-flow-in-recyclerview-items-model-view-presenter-approach-using-476420bfa22f – saiedmomen Nov 19 '18 at 09:25
  • @RohitSingh thanks! It seems the trade-off of RecyclerView is the inability of declaring content in the view. – Jasper Nov 19 '18 at 09:29
  • I did not understand the trade-off ? What are you exactly suggesting? Was the suggested link helpful ? – Rohit Singh Nov 19 '18 at 11:54
  • Yes, very helpful! That's why I upvoted. I would still prefer to declare bindings in the view, not in the Adapter/ViewHolder, that is what I mean with trade-off: it seems you can not use declarative binding with RecyclerView. – Jasper Nov 19 '18 at 12:08

0 Answers0