The RecyclerView.ViewHolder
class has a field that is public final View itemView
. It says that the onBindViewHolder
method should update the contents of the itemView
to reflect the item at the given position .
Doesn’t the final
modifier indicate that the value of this field cannot change ?
The code below is from the textbook :
public class ViewHolder extends RecyclerView.ViewHolder {
...
@Override
public int getItemCount() {
...
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
...
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
...
}
}
Why do these methods here can override the methods in the RecyclerView.Adapter
class which is derived from the RecyclerView.ViewHolder
class ?
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html
Could someone explain it ?
Thank you.
Doesn’t the final modifier indicate that the value of this field cannot change ?
The final modifier on a View indicate that you can only initiate the view once (by creating a new View(context) or inflate a view from an xml file). But you can still modify the view property. (i.e. your view contains a TextView, you can set the text)
For your second question, the text book is not very precise about how to implement the adapter with a view holder. Here is a simple implementation of an adapter with a custom view holder.
public class Adapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
private List<String> titles;
public Adapter(List<String> titles) {
this.titles = titles;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
return new MyViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_view, viewGroup, false));
}
@Override
public void onBindViewHolder(MyViewHolder myViewHolder, int i) {
String title = titles.get(i);
myViewHolder.title.setText(title);
}
@Override
public int getItemCount() {
return titles.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title_TV);
}
}
}
and the xml file for it:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="@+id/title_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
You can see that if you extend RecyclerView.Adapter, you will have to override these 3 methods.
Hope this will help you to understand more the RecyclerView.