[Android]FlowLayout:流式布局的应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gods_magic/article/details/81504393

一、应用

流式布局即控件根据ViewGroup的宽,自动的往右添加,如果当前行剩余空间不足,则自动添加到下一行。经常应用于搜索历史以及热搜等界面。

二、实现

1.FlowLayout.java

只要是重写onMeasure和onLayout两个函数。

  • onMeasure主要是对子控件的width和height进行测量
  • onLayout主要是对子控件进行布局
public class FlowLayout extends ViewGroup {
    public FlowLayout(Context context) {
        super(context);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected LayoutParams generateLayoutParams(
            LayoutParams mLayoutParams) {
        return new MarginLayoutParams(mLayoutParams);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }

    /**
     * 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 获得它的父容器为它设置的测量模式和大小
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        // 如果是warp_content情况下,记录宽和高
        int width = 0;
        int height = 0;
        //记录每一行的宽度,width不断取最大宽度
        int lineWidth = 0;
        //每一行的高度,累加至height
        int lineHeight = 0;

        int cCount = getChildCount();
        // 遍历每个子元素
        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            // 测量每一个child的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 得到child的lp
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();
            // 当前子空间实际占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin
                    + lp.rightMargin;
            // 当前子空间实际占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin
                    + lp.bottomMargin;
            /**
             * 如果加入当前child,则超出最大宽度,则得到目前最大宽度给width,累加height 然后开启新行
             */
            if (lineWidth + childWidth > sizeWidth) {
                //更新width(最大宽度)
                width = Math.max(lineWidth, width);
                //开始下一行,更新lineWidth
                lineWidth = childWidth;
                // 叠加当前高度,
                height += lineHeight;
                // 开启记录下一行的高度
                lineHeight = childHeight;
            } else {
                //不需换行,累加lineWidth
                lineWidth += childWidth;
                //lineHeight取最大高度
                lineHeight = Math.max(lineHeight, childHeight);
            }
            // 如果是最后一个,则将当前记录的最大宽度和当前lineWidth做比较
            if (i == cCount - 1) {
                //防止最后一个的宽度最大,更新width为最大
                width = Math.max(width, lineWidth);
                //保证height最终大于所有lineHeight的累加值
                height += lineHeight;
            }

        }
        //创建view
        //然后根据所有childView的测量得出的宽和高得到该ViewGroup如果设置为wrap_content时的宽和高。
        //最后根据模式,如果是MeasureSpec.EXACTLY则直接使用父ViewGroup传入的宽和高,否则设置为自己计算的宽和高。
        setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth
                : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight
                : height);

    }

    /**
     * 存储所有的View,按行记录
     */
    private List<List<View>> mAllViews = new ArrayList<>();
    /**
     * 记录每一行的最大高度
     */
    private List<Integer> mLineHeight = new ArrayList<>();

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mAllViews.clear();
        mLineHeight.clear();

        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        // 存储每一行所有的childView
        List<View> lineViews = new ArrayList<>();
        int cCount = getChildCount();
        // 遍历所有的孩子
        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 如果已经需要换行
            if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth > width) {
                // 记录这一行所有的View以及最大高度
                mLineHeight.add(lineHeight);
                // 将当前行的childView保存,然后开启新的ArrayList保存下一行的childView
                mAllViews.add(lineViews);
                lineWidth = 0;// 重置行宽
                lineViews = new ArrayList<>();
            }
            /**
             * 如果不需要换行,则累加
             */
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin
                    + lp.bottomMargin);
            lineViews.add(child);
        }
        // 记录最后一行
        mLineHeight.add(lineHeight);
        mAllViews.add(lineViews);

        int left = 0;
        int top = 0;
        // 得到总行数
        int lineNums = mAllViews.size();
        for (int i = 0; i < lineNums; i++) {
            // 每一行的所有的views
            lineViews = mAllViews.get(i);
            // 当前行的最大高度
            lineHeight = mLineHeight.get(i);

            // 遍历当前行所有的View
            for (int j = 0; j < lineViews.size(); j++) {
                View child = lineViews.get(j);
                if (child.getVisibility() == View.GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child
                        .getLayoutParams();

                //计算childView的left,top,right,bottom
                int lc = left + lp.leftMargin;
                int tc = top + lp.topMargin;
                int rc = lc + child.getMeasuredWidth();
                int bc = tc + child.getMeasuredHeight();

                child.layout(lc, tc, rc, bc);

                left += child.getMeasuredWidth() + lp.rightMargin
                        + lp.leftMargin;
            }
            left = 0;
            top += lineHeight;
        }
    }
}

2.history_layout.xml

在布局中引入FlowLayout控件。

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginEnd="29.42dp"
        android:layout_marginStart="29.42dp">

        <mysummary.myutils.FlowLayout
            android:id="@+id/FlowLayout"
            android:layout_width="wrap_content"
            android:layout_height="match_parent">
        </mysummary.myutils.FlowLayout>
</LinearLayout>

3.history_textview_item.xml

设置子控件的格式

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/history_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="15dp"
    android:layout_marginRight="12.57dp"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/search_history_text"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="6.13dp"
            android:layout_marginTop="-4dp"
            android:ellipsize="end"
            android:fontFamily="sec-roboto-condensed"
            android:singleLine="true"
            android:text="TEXT"
            android:textColor="@color/colorWhite100"
            android:textSize="15.94dp" />
    </LinearLayout>
</LinearLayout>

4.Activity.java

在java文件中,根据读取历史记录的size,将每条记录在FlowLayout下显示出来。

for (int i = 0; i < mHistoryList.size(); i++) {
            // 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置
            // 当该view被添加到父view当中时,这些layout属性会自动生效。
            View view = LayoutInflater.from(this).inflate(R.layout.view_search_history_item, mFlowLayout, false);
            TextView mText = view.findViewById(R.id.search_history_text);

            final String text = mHistoryList.get(i);
            if (text != null) {
                mText.setText(text);
                //添加历史记录点击事件
                //...

                mFlowLayout.addView(view);
            }
}

以上便是流式布局FlowLayout的简单应用以及实现。

猜你喜欢

转载自blog.csdn.net/Gods_magic/article/details/81504393
今日推荐