I'm a junior in android developpement and i'm looking for the best implementation of my Viewholder / onBindViewHolder.
Here is what android studio give us when he build a fragment (list) :
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
//some code
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.item_number);
mContentView = (TextView) view.findViewById(R.id.content);
}
//some code
}
}
Why the item is send to the ViewHolder ? And why he isn't used in the onBindViewHolder for updating TextViews ? Like this :
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
//some code
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(holder.mItem.id);
holder.mContentView.setText(holder.mItem.content);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.item_number);
mContentView = (TextView) view.findViewById(R.id.content);
}
//some code
}
}
And finnaly what i was doing for the moment. Not sending the item to the ViewHolder :
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
//some code
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
DummyItem mItem = mValues.get(position);
holder.mIdView.setText(mItem.id);
holder.mContentView.setText(mItem.content);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.item_number);
mContentView = (TextView) view.findViewById(R.id.content);
}
//some code
}
}
What's the best way ?
I don't know exactly what you're talking about but from what I understand, Your view holder can contain all the the UI and methods and logics, however I prefer the third method as it is more clear than the rest 2.
That being said please Look HERE AdaMc331 explains how do these methods work and how should you use them.