Recycleview显示不同的视图类型

时间:2014-11-20 13:48:14

标签: android android-recyclerview

我使用recycleview显示列表。我想知道我们如何展示不同类型的观点?如同,不同的ViewHolders在同一个适配器中

在简单的listview中,我们使用了getItemViewType(),在recycleview中有什么不同的东西吗?

2 个答案:

答案 0 :(得分:38)

要创建具有多种视图类型的RecyclerView,只需实施getItemViewType()两个ViewHolder,并处理viewType和{{onCreateViewHolder()中的bindViewHolder()参数1}}。

简短的例子:

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;
            ...
        }
    }
}

答案 1 :(得分:-2)

编译'com.firebaseui:firebase-ui-database:1.0.1'     编译'com.firebaseui:firebase-ui-storage:1.0.1'将其放入gradle