Android自定义View —流式布局FlowLayout

源码地址:(免费)案例源码

1.应用背景及说明

现在大部分商城类app都要用到流式布局,就是对不规则的子view进行布局排列。
自定义流式布局不外乎两点,重写onMeasure方法和onLayout方法。大部分代码我都写了注释,但还是有一些比较细节的地方,我还会抽取出来重点讲。
废话不多说,先上图。这才是正确的图

在这里插入图片描述

2.代码架构

结构比较简单,几个类而已,就不写了,直接上图吧!

在这里插入图片描述

3.代码分析

FlowLayout.java

以下代码还有一个很重要的地方在xml中,即android:layout_height="wrap_content"
就是这样:
在这里插入图片描述

onMeasure方法:
就干了两件事,一件是度量孩子,另一件是度量自己。在这其中保存了一些数据。
onLayout方法:
就干了一件事,拿到onMeasure方法中得到的数据,进行布局摆放。
为什么这里不要用onDraw方法呢?
众所周知,onDraw是进行绘制的,但这里我已经得到的大小,并且把它摆放再合适的位置,完全就不需要绘制这个方法。
基本上每个代码都写了注释,重点讲一下易错和需要注意的地方

package com.example.flowlayout.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

public class FlowLayout extends ViewGroup {
    
    

    private static final String TAG = "FlowLayout";
    //统一设置间隔,比较方便
    private int horizontalSpace = dip_2px(16);
    private int verticalSpace = dip_2px(8);


    private int dip_2px(int dpValue) {
    
    
        float scale = getResources().getDisplayMetrics().density;
        return (int) (scale * dpValue + 0.5f);
    }
    //每次添加整行的view,相当于一个二维表
    List<List<View>> widList;
    //每一行的行高
    List<Integer> heiList = new ArrayList<>();
    //一行的view
    List<View> lineList;

    public FlowLayout(Context context) {
    
    
        this(context, null);
    }

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

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    
    
        super(context, attrs, defStyleAttr);
    }
 	
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
    
        int selWidth = MeasureSpec.getSize(widthMeasureSpec);
        int selHeight = MeasureSpec.getSize(heightMeasureSpec);
        //目前宽高
        int curWidth = 0;
        int curHeight = 0;
        //如果他写在外面,就会多一倍的行数,因为onMeasure方法要执行两次,但应该是能解决这个测量优化问题
        widList = new ArrayList<>();
        //记录一行的view
        lineList = new ArrayList<>();
        int childCount = getChildCount();
        //爸爸的padding
        int PLeft = getPaddingLeft();
        int PTop = getPaddingTop();
        int PRight = getPaddingRight();
        int PBottom = getPaddingBottom();
        //儿子需要的最大长宽,当模式为AT_MOST时,就需要用到这个变量。
    	int childMostWidth = 0;
    	int childMostHeight = 0;
        for (int i = 0; i < childCount; i++) {
    
    
            View childView = getChildAt(i);

            MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
            //第二个参数:父View左右(上下)Padding+子View左右(上下)Margin, 源码也没说详细, 但是你能看系统布局的源码(LinearLayout),
            // 最好不设置padding。
            //感觉不太好操作
            int childWidMeasureSpec = getChildMeasureSpec(widthMeasureSpec, lp.leftMargin + lp.rightMargin
                    + PLeft + PRight, lp.width);
            int childHeiMeasureSpec = getChildMeasureSpec(heightMeasureSpec, lp.topMargin + lp.bottomMargin
                    + PTop + PBottom, lp.width);
            Log.d(TAG, "onMeasure: " + lp.leftMargin + "---" + PLeft);
            childView.measure(childWidMeasureSpec, childHeiMeasureSpec);

            //得到子view的长宽
            int childWidth = childView.getMeasuredWidth();
            int childHeight = childView.getMeasuredHeight() ;

            //换行操作
            if (curWidth + childWidth + horizontalSpace> selWidth) {
    
    
                //添加这一行的view及行高
                widList.add(lineList);
                heiList.add(curHeight);

                //记录最大的行宽及行高
                childMostWidth = Math.max(childMostWidth, curWidth + horizontalSpace);
                childMostHeight += curHeight + verticalSpace;
                //清空,重新记录
                lineList = new ArrayList<>();
                curHeight = 0;
                curWidth = 0;
                Log.d(TAG, "onMeasure: " + 1);

            }
            //添加每个子view,这个需要放在第二个if的上方,
            //因为第二个if语句执行完后,没必要再操作了。
            lineList.add(childView);
            //当前行的宽度及高度
            curWidth += childWidth + horizontalSpace;
            curHeight = Math.max(curHeight, childHeight );
            //最后一行执行的操作,因为他不可能执行第一个if语句
            if (curWidth < selWidth && i == childCount - 1) {
    
    
                widList.add(lineList);
                heiList.add(curHeight);
                Log.d(TAG, "onMeasure: " + 2);

                childMostWidth = Math.max(childMostWidth, curWidth);
                childMostHeight += curHeight + verticalSpace;
            }


        }
        //模式
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        //模式,打个log就知道是爸爸的还是儿子的模式了
        //onMeasure: 宽的mode:MeasureSpec.AT_MOST
        Log.d(TAG, "onMeasure: 宽的mode:" + (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST?
                "MeasureSpec.AT_MOST": "MeasureSpec.UNSPECIFIED"));
		//这里为什么要这么操作呢?因为这个viewgroup既要看他爸爸眼色行事
		//还要看它儿子眼色行事,所以我需要判断它的模式是什么,是跟爸爸一致,
		//还是跟儿子一致
        int finallyWidth = (widthMode == MeasureSpec.EXACTLY ? selWidth : childMostWidth);
        int finallyHeight = (heightMode == MeasureSpec.EXACTLY ? selHeight : childMostHeight);
        //测量自己
        setMeasuredDimension(finallyWidth, finallyHeight);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
    
    
        int curL = 0 ;
        int curT = 0;
        for (int i = 0; i < widList.size(); i++) {
    
    
            List<View> lineView = widList.get(i);
            Log.d(TAG, "onLayout: " + widList.size() + "---" + lineView.size());
            for (int j = 0; j < lineView.size(); j++) {
    
    
                View childView = lineView.get(j);
                int left = curL ;
                int top = curT ;
                if (j == 0) {
    
    
                    left = curL + horizontalSpace;
                }
                int right = left + childView.getMeasuredWidth();
                int bottom = top + childView.getMeasuredHeight();
                //如是是把 widList = new ArrayList<>()写在onMeasure     外        ,会有4行
                // 那么第一行和第三行的数据相同,所以相当于重新layout了, 所以第一行就为空了,就会出现这种情况

                childView.layout(left, top, right, bottom);
                curL = right + horizontalSpace;

            }
            curL = 0;
            curT = curT + heiList.get(i) + verticalSpace;
            lineView.clear();
        }
        //直接clear
        widList.clear();
        heiList.clear();
        lineList.clear();

    }

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

1.关于间隔的设置,建议统一设置间隔,比较方便。不要在xml中设置,可能会引起间隔不统一,就不好看了。

2.如果把这两个参数放外面,先看下面的图

//儿子需要的最大长宽,当模式为AT_MOST时,就需要用到这两个变量。
int childMostWidth = 0;
int childMostHeight = 0;

怎么解释呢?emmm…要结合第三点,即onMeasure方法的二次测量,如果放在里面,childMostHeight 每次onMeasure都会置0,也就是高度的问题,它只能观察两行
但放在外面就不同。childMostHeight 一直在增加,重新onMeasure,并没有赋为0,他就能观察到四行

3.关于onMeasure方法的二次测量的问题。这个可以找资料看看,就是说onMeasure方法会执行两次。但是这会造成一些问题。
比如:如果你把用来记录数据的变量放在onMeasure外面且在外面初始化,就会造成数据翻倍的问题。比如说这个变量: widList

//每次添加整行的view,相当于一个二维数组
List<List> widList;

解决方法:当然就是需要我们在onMeasure方法中进行成员变量的初始化。
尽管我们测量了多次,但每次测量前我们都将它初始化了

关于第2,3点,如果childMostHeight 放在onMeasure方法外面,且 widList在onMeasure方法外面初始化,那么,就是这个图
在这里插入图片描述
在这里插入图片描述

4 . 当然,可能有人会有疑问,为什么是两空行,不应该是四行都有数据吗?
我们需要知道的是,1,3两行, 2,4两行数据是一样的。
在onLayout方法中,
在layout时,因为childView一样,同一个childView进行layout,你说会怎么办?总不可能一个childView layout在不同的地方吧!当然是第一行的数据会定位到第三行,第一行就会为空了。

5.其实是还有几个需要注意的地方,但我都在代码中给的很详细了,这里我就不说了。开头我也给了我写的源码,你们可以看看,借鉴借鉴。

6.留给大家一个疑问,怎么写,才会出现这种错误,没有数据显示,看下图:
在这里插入图片描述
在这里插入图片描述

4.总结:

都说的很详细了。
一个字:

猜你喜欢

转载自blog.csdn.net/zk2000416/article/details/106049656