18

I'm using the recycleview to show a list. I was wondering how do we show different types of views? As in, different ViewHolders int the same adapter

In the simple listview we used getItemViewType(), anything different in the recycleview?

1

2 Answers 2

38

To create RecyclerView with multiple view type just implement getItemViewType(), two different ViewHolders and take care of the viewType parameter in onCreateViewHolder() and bindViewHolder().

Short example:

public class MultipleViewTypesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int VIEW_TYPE_FIRST = 0; private static final int VIEW_TYPE_SECOND = 1; class ViewHolderFirst extends RecyclerView.ViewHolder { ... } class ViewHolderSecond extends RecyclerView.ViewHolder { ... } @Override int getItemViewType(int position) { return position % 2; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case VIEW_TYPE_FIRST: return new ViewHolderFirst(...); case VIEW_TYPE_SECOND: return new ViewHolderSecond(...); ... } } @Override public void bindViewHolder(RecyclerView.ViewHolder holder, int position) { switch (getItemViewType(position)) { case VIEW_TYPE_FIRST: ViewHolderFirst viewHolderFirst = (ViewHolderFirst)holder; ... break; case VIEW_TYPE_SECOND: ViewHolderSecond viewHolderSecond = (ViewHolderSecond)holder; ... break; ... } } } 
Sign up to request clarification or add additional context in comments.

3 Comments

What would you return for default case in onCreaeViewHolder?
@GokhanArik you choose. I think the best choice is to return the empty adapter, as the list used to populate adapter might be empty.
Google suggest you display an Image or helpful text, when there is no content to display. Follow the material design spec on empty states for more details.
-2

compile 'com.firebaseui:firebase-ui-database:1.0.1' compile 'com.firebaseui:firebase-ui-storage:1.0.1' put that in gradle

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.