This will be theoretical question.
As everyone we use RecyclerView in many parts of the app. Sometimes RecyclerView contains different items, not only image for example, but ads, hints etc. And that's why we can use getViewType() method in Adapter.
But problem occurs when we have many viewTypes and binding this in Adapter is not elegant. So here is the question, is it nice and good pattern to bind data in ViewHolder?
Let's say we have list of apps.
Every app has name for simplicity. Our ViewHolder looks like this:
class AppViewHolder extends RecyclerView.ViewHolder {
public TextView nameText;
AppViewHolder(View itemView) {
super(itemView)
nameText = (TextView) itemView.findViewById(R.id.text_name);
}
}
Now we could add bind method:
public void bind(App app) {
nameText.setText(app.getName());
}
Is it good pattern?
Another solution would be using ViewModel. Because we have different items in RecyclerView, our Adapter could contain list of class which is base class for every ViewModel.
So basic class is:
class RecyclerViewItem {}
Now class which is ViewModel for App.
class AppRecyclerViewItem extends RecyclerViewItem {
App app;
...
}
and our Adapter just has list of RecyclerViewItems:
class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<RecyclerViewItem> items;
...
}
So with this approach (I mean using ViewModel) is it better to add bind method in ViewHolder, or in ViewModel?