FlowLayout:Android自定义ViewGroup实现

需求

我们需要实现一个自定义的Layout,该Layout可以容纳若干个宽高不等的子元素,元素按照从左到右的顺序排列,当元素超出屏幕显示范围时,换一行继续显示,like this


FlowLayout:Android自定义ViewGroup实现_第1张图片

View和ViewGroup

Android的界面都是由ViewViewGroup及其派生类组合而成,其中,View是ViewGroup及其他UI组件的基类。ViewGroup是放置View的容器,在编写xml布局文件的时候,View所有以layout开头的属性都是提供给ViewGroup的,ViewGroup根据这些属性来给childView计算出测量模式和建议的宽高,并将childView绘制在屏幕上的适当位置

UI是怎样被绘制出来的

UI组件渲染过程可分为三个阶段:测量、布局、绘制.

Measure过程

Measure过程的任务是根据ViewGroup给的参数计算出视图自身的大小,在View中与Measure过程相关的方法有measure()onMeasure()setMeasureDimension(),其中onMeasure()是我们需要在自定义视图的时候重写的方法,在measure()方法中,onMeasure()被调用,在onMeasure()计算完毕后,调用setMeasureDimension()设置自身大小。
自身大小的计算结果取决于视图本身所占区域的大小及ViewGroup传递过来的MeasureMode值,其中MeasureMode可能取值为UNSPECIFIEDEXACTLYAT_MOST

UNSPECIFIED

表示childView可将自身大小设置为自身想要的任意大值,一般出现于AdapterView的item的高度属性中

EXACTLY

表示childView应该将自身大小设置为ViewGroup指定的大小,当View指定了自身宽或高为精确的值或match_parent时,ViewGroup会传入该Mode

AT_MOST

表示childView可以在一个限定的最大值范围内设置自己的大小,当View指定自身宽或高为wrap_content时,ViewGroup会传入该Mode
Measure过程结束后,视图大小即被确定。

Layout过程

Layout过程的任务是决定视图的位置,framework调用View的layout()方法来计算位置,在layout()方法中,onLayout()方法会被调用,这个方法是需要View的派生类重写的,在此实现布局逻辑。
Layout是一个自顶向下递归的过程,先布局容器,再布局子视图,因此,ViewGroup的位置一定程度上决定了它的childView的位置。
Layout过程结束后,视图在屏幕上的位置即被确定。

Draw过程

Draw过程的任务是根据视图的尺寸和位置,在相应的区域内绘制自身样式。同样的,framework会调用onDraw()方法,我们需要重写onDraw()方法实现绘制逻辑,在View中,可以通过调用invalidate()方法触发视图重绘。

让View支持Padding和Margin

如上文所说,所有以layout开头的属性都是交由容器处理的,layout_margin就是这样一个属性,在自定义View中可通过getLayoutParams()返回的LayoutParams对象来获取到视图各个方向的margin值,容器只需在layout过程中将margin值作为偏移量加入即可实现将视图放置在正确位置。
Padding是视图的自有属性,描述其各个方向边界到内部内容的距离,在代码中可通过getPaddingTop(/Left/Right/Bottom)()来获取各个方向的padding值,在Measure过程中,需要注意View尺寸包含内容区域加上padding区域,padding区域内的内容将不会被绘制。

Step by Step实现需求

onMeasure

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int contentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int contentHeight = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        //Padding支持
        int topOffset = getPaddingTop();
        int leftOffset = getPaddingLeft();
        int selfWidth = 0, selfHeight = 0;
        int currentLineWidth = 0, currentLineHeight = 0;
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE)
                continue;
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = Math.max(child.getMeasuredWidth(), getSuggestedMinimumWidth()) + layoutParams.leftMargin + layoutParams.rightMargin;
            int childHeight = Math.max(child.getMeasuredHeight(), getSuggestedMinimumHeight()) + layoutParams.topMargin + layoutParams.bottomMargin;
            if (currentLineWidth + childWidth > contentWidth  - getPaddingLeft() - getPaddingRight()) {
                //需要另起一行
                currentLineWidth = Math.max(currentLineWidth,childWidth);
                selfWidth = Math.max(selfWidth, currentLineWidth);
                currentLineWidth = childWidth;
                selfHeight += currentLineHeight;
                currentLineHeight = childHeight;
                //Measure的时候顺便把位置计算出来
                child.setTag(new Location(child, leftOffset, selfHeight + topOffset, childWidth + leftOffset, selfHeight + child.getMeasuredHeight() + topOffset));
            } else {
                //不需要换行
                child.setTag(new Location(child, currentLineWidth + leftOffset, selfHeight + topOffset, currentLineWidth + child.getMeasuredWidth() + topOffset, selfHeight + child.getMeasuredHeight() + topOffset));
                currentLineWidth += childWidth;
                currentLineHeight = Math.max(currentLineHeight, childHeight);
            }
            if (i == childCount - 1) {
                //到最后一个child的时候更新高度
                sselfWidth = Math.max(currentLineWidth, selfWidth) + getPaddingRight() + getPaddingLeft();
                selfHeight += currentLineHeight + getPaddingTop() + getPaddingBottom();
            }
        }
        setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? contentWidth : selfWidth,
                heightMode == MeasureSpec.EXACTLY ? contentHeight : selfHeight);
    }

经过如上处理,ViewGroup的尺寸和childView的位置便被计算出来,并且ViewGroup可根据childView排列情况自动调整自身宽高。

onLayout

@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                Location location = (Location) child.getTag();
                child.layout(location.left, location.top, location.right, location.bottom);
            }
        }
    }

onMeasure()中我们已经顺手计算出了各个childView的位置信息,所以在Layout步骤中只需将其按照位置摆放到相应区域即可。

draw

draw方法是由framework调用,在ViewGroup的onDraw()方法中绘制的内容最后会被作为ViewGroup的背景,所以如果需要更改背景内容可重写该方法。draw()中会递归调用childView的onDraw()方法,调用完毕后ViewGroup本身和childView都绘制完毕,一次渲染过程到此结束。

附加特性

可通过对ViewGroup设置LayoutAnimation来为childView显示的过程附加动画,一个简单的例子:

public FlowLayout(Context context) {
        super(context);
        setLayoutAnimation(
                new LayoutAnimationController(AnimationUtils.loadAnimation(
                        getContext(), R.anim.list_animation), 0.3f));
    }

可以重写addView()方法为动态添加的View附加动画,重写removeView()方法实现移除View时的附加动画。

实现效果

FlowLayout:Android自定义ViewGroup实现_第2张图片

你可能感兴趣的:(FlowLayout:Android自定义ViewGroup实现)