RecyclerView系列之七:LayoutManager

在RecyclerView中,我们可以通过LayoutManager控制其布局的显示方式,实现横向ListView、GridView、瀑布流等常见效果.
首先我们来看一看RecyclerView.LayoutManager的继承结构:

RecyclerView.LayoutManager是一个抽象类,其直接的实现类有LinearLayoutManager、StaggeredGridLayoutManager,而LinearLayoutManager也有一个子类GridLayoutManager.

1)通过LinearLayoutManager:我们可以实现横向、纵向的列表效果
2)通过GridLayoutManager:我们可以实现像GridView一样的网格布局
3)通过StaggeredGridLayoutManager:我们可以实现瀑布流的效果

一、LinearLayoutManager

1、纵向ListView效果

纵向ListView效果

2、横向ListView效果

item的布局中TextView的android:layout_width,android:layout_height对调

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="#ff33b5e5"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tv"
        android:layout_width="40dp"
        android:layout_height="match_parent"
        android:gravity="center"
        tools:text="别看了,我就是一个TextView" />
</RelativeLayout>
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
  //分隔线也改个方向
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL));

ok,就是这么简单,看一下效果图



是不是很简单!!!

二、GridLayoutManager

1、构造方法

public GridLayoutManager(Context context, int spanCount) {
        super(context);
        setSpanCount(spanCount);
}
    /**
     * @param spanCount 网格中的列数
     * @param orientation   HORIZONTAL或VERTICAL,实现横向GridView、纵向GridView效果               
     * @param reverseLayout 为true时,布局由下向上/由右向左
     */
 public GridLayoutManager(Context context, int spanCount, int orientation,
            boolean reverseLayout) {
        super(context, orientation, reverseLayout);
        setSpanCount(spanCount);
}

2、GridView效果

item的布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="#ff33b5e5"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:gravity="center"
        tools:text="别看了,我就是一个TextView" />
</RelativeLayout>
layoutManager = new GridLayoutManager(this,4);
//   系统默认的分隔线在这里就不适用了,需注释掉

效果图:


3、GridLayoutManager的分隔线

关于分隔线的原理在RecyclerView系列之二:添加分隔线中已经介绍了,今天这里介绍GridLayoutManager的分隔线.
先上效果图:

public class MyGridItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[] { android.R.attr.listDivider };
    private Drawable mDivider;

    public MyGridItemDecoration (Context context) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state){
        drawHorizontal(c, parent);
        drawVertical(c, parent);
    }


    private int getSpanCount(RecyclerView parent){
        int spanCount = -1;
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager){
            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager){
            spanCount = ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
        }
        return spanCount;
    }

    /**
     * 确定每个分隔线的top 、bottom 、left 、right 
     *        例如:条目A,就确定上图2的top 、bottom 、left 、right 
     */
    public void drawHorizontal(Canvas c, RecyclerView parent){
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++){
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getLeft() - params.leftMargin;
            final int right = child.getRight() + params.rightMargin + mDivider.getIntrinsicWidth();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    /**
     * 确定每个item 竖向分隔线的top 、bottom 、left 、right 
     *         例如:条目A,就确定上图1的top 、bottom 、left 、right 
     */
    public void drawVertical(Canvas c, RecyclerView parent){
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++){
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int top = child.getTop() - params.topMargin;
            final int bottom = child.getBottom() + params.bottomMargin;
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicWidth();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    /**
     * 是否是最后一列
     */
    private boolean isLastColum(RecyclerView parent, int pos, int spanCount,int childCount){
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            if ((pos + 1) % spanCount == 0){// 如果是最后一列,则不需要绘制右边
                return true;
            }
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            int orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
            if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                if ((pos + 1) % spanCount == 0) {// 如果是最后一列,则不需要绘制右边
                    return true;
                }
            } else {
                childCount = childCount - childCount % spanCount;
                if (pos >= childCount)// 如果是最后一列,则不需要绘制右边
                    return true;
            }
        }
        return false;
    }

    /**
     * 是否是最后一行
     */
    private boolean isLastRaw(RecyclerView parent, int pos, int spanCount,int childCount){
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager){
            childCount = childCount - childCount % spanCount;
            if (pos >= childCount)// 如果是最后一行,则不需要绘制底部
                return true;
        } else if (layoutManager instanceof StaggeredGridLayoutManager){
            int orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();

            if (orientation == StaggeredGridLayoutManager.VERTICAL){ // StaggeredGridLayoutManager 且纵向滚动
                childCount = childCount - childCount % spanCount;
                if (pos >= childCount)// 如果是最后一行,则不需要绘制底部
                    return true;
            } else{// StaggeredGridLayoutManager 且横向滚动
                if ((pos + 1) % spanCount == 0){// 如果是最后一行,则不需要绘制底部
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = parent.getChildAdapterPosition(view);
        int spanCount = getSpanCount(parent);
        int childCount = parent.getAdapter().getItemCount();
        int pos = position;
        if (isLastRaw(parent, pos, spanCount, childCount)) {// 如果是最后一行,则不需要绘制底部
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        } else if (isLastColum(parent, pos, spanCount, childCount)) {// 如果是最后一列,则不需要绘制右边
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else{
            outRect.set(0, 0, mDivider.getIntrinsicWidth(),mDivider.getIntrinsicHeight());
        }
    }
}

Activity中:

 mRecyclerView.addItemDecoration(new MyGridItemDecoration(this));

三、StaggeredGridLayoutManager

1、构造方法

    /**
     * @param spanCount  
     *                   方向为VERTICAL时spanCount代表多少列
     *                   方向为HORIZONTAL时spanCount代表多少行
     * @param orientation       VERTICAL或者HORIZONTAL
     */
    public StaggeredGridLayoutManager(int spanCount, int orientation) {
        mOrientation = orientation;
        setSpanCount(spanCount);
        setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE);
        mLayoutState = new LayoutState();
        createOrientationHelpers();
    }

2、普通GridView效果

如果仅仅是把layoutManager 改变为StaggeredGridLayoutManager,item的高度还是固定一样的话,效果和网格布局就一样了

layoutManager = new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);

3、瀑布流效果

要实现瀑布流的效果,每个item的高度当然要不一样了

1)item布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ff33b5e5">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_margin="3dp"
        android:gravity="center"
        tools:text="别看了,我就是一个TextView" />

</RelativeLayout>

2)Adapter中
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MyViewHolder> {

    private Context mContext;
    private List<String> mDatas;

    //这里我们定义一个随机高度的集合,确定随机高度
    private List<Integer> mHeights;

    public MainAdapter(Context context, List<String> mDatas) {
        this.mContext = context;
        this.mDatas = mDatas;

     //为随机高度的集合添加数据
        mHeights = new ArrayList<Integer>();
        for (int i = 0; i < mDatas.size(); i++){
            mHeights.add( (int) (100 + Math.random() * 300));
        }
    }


    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false));
    }

    /**
     * 在这里为每个item动态设置高度
     */
    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        ViewGroup.LayoutParams params = holder.tv.getLayoutParams();
        params.height = mHeights.get(position);
        holder.itemView.setLayoutParams(params);

        holder.tv.setText(mDatas.get(position));
    }

    @Override
    public int getItemCount() {
         return mDatas.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tv;

        public MyViewHolder(View view) {
            super(view);
            tv = (TextView)itemView.findViewById(R.id.tv);
        }
    }
}

这里需要注意的是,虽然是随机高度,但是不要直接在onBindViewHolder设置随机高度,像下面这样:

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        ViewGroup.LayoutParams params = holder.tv.getLayoutParams();
        params.height = (int) (100 + Math.random() * 300);
        holder.itemView.setLayoutParams(params);

        holder.tv.setText(mDatas.get(position));
    }

因为在复用时会调用onBindViewHolder()方法填充数据,如果在这里重新给item设置高度,会出现滑动过程中item高度一直变换、item还会交换位置的问题.

3)Activity中
layoutManager = new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);

//这里分隔线已经不再适应,在item布局文件中我已经设置了margin代替分隔线的作用
4)效果图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,566评论 25 707
  • 今天有很多事无法停止思考,有很多话我却忍着不说。心里揣着事的时候,很难掩饰住。 为了不让自己思考,我下午和妈咪出去...
    轩轩糖阅读 233评论 0 0
  • 先祖, 你罪恶的头颅 是否还满盈浓稠的朝露 血红、滚烫、流珠 如何使你闪亮 就连太阳也望而却步 没有心事,就不要来...
    不印阅读 119评论 0 7
  • 喜欢你,只那一眼,便是万年。 喜欢你,与你无关,只因,我终究不是归人,只是过客。 08年9月 在我冒着生命危险与老...
    安佐佐阅读 389评论 0 0