RecyclerView添加Hearder

Activity中添加如下代码

     mAdapter = new MyQcBankAdapter(this);
        mRecyclerView.setAdapter(mAdapter);
        final GridLayoutManager manager = new GridLayoutManager(this, 2);

        //为RecyclerView添加头部layout
        View header = LayoutInflater.from(this).inflate(R.layout.qcbank_mybank_list_header, mRecyclerView, false);
        //修改头部layout为通栏,修改单元格所占列数,此处将两个单元格合并为一个单元格
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return mAdapter.isHeader(position) ? manager.getSpanCount() : 1;
            }
        });
        mAdapter.setHeaderView(header);
        mRecyclerView.setLayoutManager(manager);
首先我们设置了一个SpanSizeLookup,这个类是一个抽象类,而且仅有一个抽象方法getSpanSize,这个方法的返回值决定了我们每个position上的item占据的单元格个数

 

在RecycleView中添加如下代码

public static final int TYPE_HEADER = 0;
public static final int TYPE_NORMAL = 1;
private View mHeaderView;

   @Override
    public int getItemViewType(int position) {
        if (position == 0){
            //第一个item应该加载Header
            return TYPE_HEADER;
        }
        return TYPE_NORMAL;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderView != null && viewType == TYPE_HEADER) {
            return new ViewHolder(mHeaderView);
        }
        View v = LayoutInflater.from(mContext)
                .inflate(
                        R.layout.qcbank_mybank_item,
                        parent,
                        false);
        return new ViewHolder(v);
    }

    public boolean isHeader(int position) {
        return position == 0;
    }

    public View getHeaderView() {
        return mHeaderView;
    }

    public void setHeaderView(View headerView) {
        mHeaderView = headerView;
        notifyItemInserted(0);
    }

    //在这里面加载ListView中的每个item的布局
    class ViewHolder extends RecyclerView.ViewHolder {
        ViewHolder(View v) {
            super(v);
        }
    }
     
    
    @Override
    public int getItemCount() {
        return mHeaderView == null ? mDatas.size() : mDatas.size() + 1;
    }

 

posted @ 2019-05-24 10:59  夏天的小枕头  阅读(358)  评论(0编辑  收藏  举报