RecyclerView的进阶使用,一个LayoutManger下添加多种布局

写这篇文章是因为最近看了bilibili的首页,感觉是一个RecylcerView写的,于是就有了这片文章:

之所以把这俩个分开是因为,设置方式不一样,看下边介绍:


RecyclerView的进阶使用,一个LayoutManger下添加多种布局_第1张图片

首先定义多种item布局:

@Override

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE1) {//list类型
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.reclycer_layout, parent, false);
            return new ListHolder(view);
        } else if (viewType == TYPE2) {//grid类型
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.reclycer_layout, parent, false);
            return new GridHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ListHolder) {
            ListHolder listHolder = (ListHolder) holder;
            listHolder.textView.setText(list.get(position));
        } else if (holder instanceof GridHolder) {
            GridHolder gridHolder = (GridHolder) holder;
            gridHolder.textView.setText(list.get(position));
        }
    }
如果是瀑布流布局,贴一下关键代码:

 @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ListHolder) {
            ListHolder listHolder = (ListHolder) holder;
            listHolder.textView.setText(list.get(position));
          StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) listHolder.textView.getLayoutParams();
            layoutParams.setFullSpan(true);
        } else if (holder instanceof GridHolder) {
            GridHolder gridHolder = (GridHolder) holder;
            gridHolder.textView.setText(list.get(position));
        }
    }

另外一种GridLayoutManger的 ,主要是

setSpanSizeLookup()这个方法,源码如下

 /**
     * Sets the source to get the number of spans occupied by each item in the adapter.
     *
     * @param spanSizeLookup {@link SpanSizeLookup} instance to be used to query number of spans
     *                       occupied by each item
     */
    public void setSpanSizeLookup(SpanSizeLookup spanSizeLookup) {
        mSpanSizeLookup = spanSizeLookup;
    }

可以看出需要传入一个SpansizeLookup对象,接着写一个类继承这个类

设置每个Item 所占得位置 默认是1 如果你的2列 这里可以在添加头部的时候 设置为2 就会占一整行了

  class MySpanSizeLookup extends GridLayoutManager.SpanSizeLookup {

        @Override
        public int getSpanSize(int position) {
            if (position < 6) {//前6个item默认占一整行
                return 2;
            } else { //返回默认值 因为我设置的是2个默认 既2个占位一行
                return 1;
            }
        }
    }

在activity中去设置
manager = new GridLayoutManager(mContext, 2);
        manager.setSpanSizeLookup(new MySpanSizeLookup());
想要的效果就出来了。
最后LieanerLayoutMannger就更简单了,自己去试试。


你可能感兴趣的:(android)