Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does notifydatasetchanged call onCreateViewHolder when using RecyclerView

I want to use a toggle to toggle between two different views but using the same RecyclerView. Basically, once you toggle, I want the RecyclerView adapter to recall onCreateViewHolder() but this time it will use a different layout item file.

Does notifydatasetchanged() cause the adapter to rebuild itself? Or is there another way?

like image 429
AmaJayJB Avatar asked Feb 18 '15 07:02

AmaJayJB


People also ask

What does notifyDataSetChanged do in RecyclerView?

notifyDataSetChanged. Notify any registered observers that the data set has changed. There are two different classes of data change events, item changes and structural changes. Item changes are when a single item has its data updated but no positional changes have occurred.

What happens when we call notifyDataSetChanged?

notifyDataSetChanged() was called. all Adapter subclasses Adapter reference must call notifyDataSetChanged() when their underlying data has changed, to let the observing view (ListView and such) know that it should refresh itself because the data changed / there is new data.

How many times onCreateViewHolder is called?

By default it have 5.


2 Answers

I needed to have two types on Views on my RecyclerView Adapter as well, one for 'regular' mode and one for multi-select mode.

So, you can override getItemViewType to force the Adapter to call your onCreateViewHolder for all views.

Add this to the Adapter code:

public void setActionMode(ActionMode actionMode) {     this.actionMode = actionMode;     notifyDataSetChanged(); }  @Override public int getItemViewType(int position) {     return (actionMode == null ? 0 : 1); } 

Add this to the ViewHolder:

@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {     View view;     if (viewType == 0) {         view = inflater.inflate(R.layout.layout_1, parent, false);     } else {         view = inflater.inflate(R.layout.layout_2, parent, false);     }     ... } 

Since you return a different ViewType when in an ActionMode, the Adapter is forced to throw away all created views, and recreate everything again.

like image 125
marmor Avatar answered Sep 21 '22 04:09

marmor


notifyDataSetChanged() calls onBindViewHolder() in case of RecyclerView

like image 27
Android Developer Avatar answered Sep 22 '22 04:09

Android Developer