Android进阶之路Android技术知识Android开发

RecyclerView系列之七:LayoutManager

2017-05-03  本文已影响0人  滴滴滴9527

在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)效果图
上一篇下一篇

猜你喜欢

热点阅读