android recyclerview实现自动换行

最近项目中多个地方要用到自动换行,发现以往的自动换行使用很不方便,尤其是对每个item进行操作时,平时使用recyclerview比较多,所以就自定义了layoutmanager实现自动换行 ,暂时项目只是提供一个简单的思路实现自动换行,有兴趣的可以自己修改

项目地址:https://github.com/chengxk/AutoLine

使用方式和平时使用recyclerview一样 替换myLayoutManager即可


关键代码


/**
 * 自动换行布局管理
 * Created by chengxiakuan on 2016/10/14.
 */
public class MyLayoutManager extends RecyclerView.LayoutManager {

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.WRAP_CONTENT,
                RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        detachAndScrapAttachedViews(recycler);

        int sumWidth = getWidth();

        int curLineWidth = 0, curLineTop = 0;
        int lastLineMaxHeight = 0;
        for (int i = 0; i < getItemCount(); i++) {
            View view = recycler.getViewForPosition(i);

            addView(view);
            measureChildWithMargins(view, 0, 0);
            int width = getDecoratedMeasuredWidth(view);
            int height = getDecoratedMeasuredHeight(view);

            curLineWidth += width;
            if (curLineWidth <= sumWidth) {//不需要换行
                layoutDecorated(view, curLineWidth - width, curLineTop, curLineWidth, curLineTop + height);
                //比较当前行多有item的最大高度
                lastLineMaxHeight = Math.max(lastLineMaxHeight, height);
            } else {//换行
                curLineWidth = width;
                if (lastLineMaxHeight == 0) {
                    lastLineMaxHeight = height;
                }
                //记录当前行top
                curLineTop += lastLineMaxHeight;

                layoutDecorated(view, 0, curLineTop, width, curLineTop + height);
                lastLineMaxHeight = height;
            }
        }

    }

}
</pre><pre name="code" class="java">调用
 MyLayoutManager layout = new MyLayoutManager();
        //必须,防止recyclerview高度为wrap时测量item高度0 layout.setAutoMeasureEnabled(true);


 recyclerView.setLayoutManager(layout);

暂时没有实现居中布局,

思路:先计算每行所有item的总宽度,使用每行的宽度减去所有item宽度和   除以二  计算出偏移量  重新布局

感觉这样很麻烦  有好的思路可以留言

http://download.csdn.net/detail/u014239858/9659889



    原文作者:四五六七八
    原文地址: https://blog.csdn.net/u014239858/article/details/52925267
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞