Does notifydatasetchanged call onCreateViewHolder when using RecyclerView

AmaJayJB picture AmaJayJB · Feb 18, 2015 · Viewed 18k times · Source

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?

Answer

marmor picture marmor · May 26, 2015

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.