Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recyclerview show different view types

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?

like image 247
Arthur Avatar asked Nov 20 '14 13:11

Arthur


People also ask

How does recycler view is different than list view?

Simple answer: You should use RecyclerView in a situation where you want to show a lot of items, and the number of them is dynamic. ListView should only be used when the number of items is always the same and is limited to the screen size.

What is the use of ViewHolder in RecyclerView Android?

A ViewHolder describes an item view and metadata about its place within the RecyclerView. RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive View.


1 Answers

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;
            ...
        }
    }
}
like image 82
erakitin Avatar answered Sep 21 '22 14:09

erakitin