RecyclerView 页眉和页脚 [英] RecyclerView header and footer

查看:36
本文介绍了RecyclerView 页眉和页脚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题可能以前有人问过,但我似乎找不到确切的答案或解决方案.我开始使用 RecyclerView,并使用 LinearLayoutManager 实现它.现在我想添加自定义页眉和页脚项目,它们与我的 RecyclerView 中的其他项目不同.页眉和页脚不应该是粘性的,我希望它们与其余项目一起滚动.有人可以指出一些如何做到这一点的例子或只是分享想法.我会很感激的.谢谢

Maybe this question has been asked before, but I could not seem to find a precise answer or solution. I started using the RecyclerView, and I implemented it using the LinearLayoutManager. Now I want to add custom header and footer items, that differ from the rest of the items in my RecyclerView. The header and footer should not be sticky, I want them to scroll with the rest of the items. Can somebody point out some example how to do this or just share ideas. I will appreciate it very much. Thx

推荐答案

在你的适配器中添加这个类:

in your adapter add this class:

private class VIEW_TYPES {
        public static final int Header = 1;
        public static final int Normal = 2;
        public static final int Footer = 3;
}

然后像这样覆盖以下方法:

then Override the following method like this:

@Override
public int getItemViewType(int position) {

    if(items.get(position).isHeader)
        return VIEW_TYPES.Header;
    else if(items.get(position).isFooter)
        return VIEW_TYPES.Footer;
    else
        return VIEW_TYPES.Normal;

}

现在在 onCreateViewHolder 方法中根据视图类型来扩展您的布局::

Now in the onCreateViewHolder method inflate your layout based on the view type::

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

    View rowView;

    switch (i) {

        case VIEW_TYPES.Normal:
            rowView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.normal, viewGroup, false);
            break;
        case VIEW_TYPES.Header:
            rowView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.header, viewGroup, false);
            break;
        case VIEW_TYPES.Footer:
            rowView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.footer, viewGroup, false);
            break;
        default:
            rowView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.normal, viewGroup, false);
            break;
    }
    return new ViewHolder (rowView);
}

现在在 onBindViewHolder 方法中根据视图持有者绑定您的布局:

Now in the onBindViewHolder method bind your layout based on the view holder:

@Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {

        int viewType = getItemViewType(position);

        switch(viewType) {

            case VIEW_TYPES.Header: // handle row header
                break;
            case VIEW_TYPES.Footer: // handle row footer
                break;
            case VIEW_TYPES.Normal: // handle row item
                break;

        }

    }

希望能帮到你.

这篇关于RecyclerView 页眉和页脚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆