自己定义控件三部曲视图篇(二)——FlowLayout自适应容器实现

前言:我最大的梦想,就是有一天。等老了坐在摇椅上回望一生,有故事给孩子们讲……。

相关文章:

Android自己定义控件三部曲文章索引》:http://blog.csdn.net/harvic880925/article/details/50995268

经过上篇的铺垫。这篇就開始正式開始FlowLayout的开发啦,还是先给大家上上效果:

从效果图中能够看到,底部container的布局方式应该是layout_width="match_parent",layout_height="wrap_content";
好了,废话不多说了,以下開始进入正规。

一、XML布局

从布局图中能够看到。FlowLayout中包括了非常多TextView.难度不大,布局代码例如以下:
先定义一个style,这是为FlowLayout中的TextView定义的:

<style name="text_flag_01">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_margin">4dp</item>
    <item name="android:background">@drawable/flag_01</item>
    <item name="android:textColor">#ffffff</item>
</style>

注意,注意!!!我们这里定义了margin。还记得上篇中怎么样提取Margin值吗?重写generateLayoutParams()函数。

以下看activity_main.xml的布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.harvic.myapplication.FlowLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ff00ff">

        <TextView
            style="@style/text_flag_01"
            android:background="@drawable/flag_03"
            android:text="Welcome"
            android:textColor="#43BBE7" />

        <TextView
            style="@style/text_flag_01"
            android:background="@drawable/flag_03"
            android:text="ITproject师"
            android:textColor="#43BBE7" />

        <TextView
            style="@style/text_flag_01"
            android:background="@drawable/flag_03"
            android:text="我真是能够的"
            android:textColor="#43BBE7" />

        <TextView
            style="@style/text_flag_01"
            android:background="@drawable/flag_03"
            android:text="你认为呢"
            android:textColor="#43BBE7" />

        <TextView
            style="@style/text_flag_01"
            android:background="@drawable/flag_03"
            android:text="不要仅仅知道挣钱"
            android:textColor="#43BBE7" />

        <TextView
            style="@style/text_flag_01"
            android:background="@drawable/flag_03"
            android:text="努力ing"
            android:textColor="#43BBE7" />

        <TextView
            style="@style/text_flag_01"
            android:background="@drawable/flag_03"
            android:text="I thick i can"
            android:textColor="#43BBE7" />

        </com.example.harvic.myapplication.FlowLayout>
</LinearLayout>

这里注意两点。FlowLayout的android:layout_width设置为"match_parent"。android:layout_height设置为""wrap_content";同一时候,我们为FlowLayout加入背景来明显看出我们计算出来的所占区域大小。

二、提取margin与onMeasure()重写

1、提取margin

上篇我们讲过要提取margin,就一定要重写generateLayoutParams

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

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

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

具体为什么我们就不再讲了。上篇已经讲的非常熟悉了,以下就看看怎样在onMeasure()中计算当前container所占的位置大小。

2、重写onMeasure()——计算当前FlowLayout所占的宽高

这里就要重写onMeasure()函数。在当中计算全部当前container所占的大小。
要做FlowLayout,首先涉及以下几个问题:
(1)何时换行
从效果图中能够看到。FlowLayout的布局是一行行的,假设当前行已经放不下下一个控件。那就把这个控件移到下一行显示。

所以我们要有个变量来计算当前行已经占领的宽度,以推断剩下的空间是否还能容得下下一个控件。

(2)、怎样得到FlowLayout的宽度
FlowLayout的宽度是全部行宽度的最大值。所以我们要记录下每一行的所占领的宽度值,进而找到全部值中的最大值。
(3)、怎样得到FlowLayout的高度
非常显然,FlowLayout的高度是每一行高度的总和,而每一行的高度则是取该行中全部控件高度的最大值。

原理到这里就讲完了,以下看看代码:

(1)首先,刚进来的时候是利用MeasureSpec获取系统建议的数值的模式

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
    int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
    int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
    int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
    ………………
}

(2)然后,是计算FlowLayout所占用的空间大小
先申请几个变量:

int lineWidth = 0;//记录每一行的宽度
int lineHeight = 0;//记录每一行的高度
int height = 0;//记录整个FlowLayout所占高度
int width = 0;//记录整个FlowLayout所占宽度

然后開始计算:(先贴出代码,再细讲)

int count = getChildCount();
for (int i=0;i<count;i++){
    View child = getChildAt(i);
    measureChild(child,widthMeasureSpec,heightMeasureSpec);

    MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
    int childWidth = child.getMeasuredWidth() + lp.leftMargin +lp.rightMargin;
    int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

    if (lineWidth + childWidth > measureWidth){
        //须要换行
        width = Math.max(lineWidth,childWidth);
        height += lineHeight;
        //因为因为盛不下当前控件。而将此控件调到下一行,所以将此控件的高度和宽度初始化给lineHeight、lineWidth
        lineHeight = childHeight;
        lineWidth = childWidth;
    }else{
        // 否则累加值lineWidth,lineHeight取最大高度
        lineHeight = Math.max(lineHeight,childHeight);
        lineWidth += childWidth;
    }

    //最后一行是不会超出width范围的,所以要单独处理
    if (i == count -1){
        height += lineHeight;
        width = Math.max(width,lineWidth);
    }

}

在整个For循环遍历每一个控件时,先计算每一个子控件的宽和高,代码例如以下:

View child = getChildAt(i);
measureChild(child,widthMeasureSpec,heightMeasureSpec);

MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidth = child.getMeasuredWidth() + lp.leftMargin +lp.rightMargin;
int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

注意我们在计算控件高度和宽度时,要加上上、下、左、右的margin值。
这里一定要注意的是:在调用child.getMeasuredWidth()、child.getMeasuredHeight()之前,一定要调用measureChild(child,widthMeasureSpec,heightMeasureSpec);!!!

。在上篇中我们讲过。在onMeasure()之后才干调用getMeasuredWidth()获得值。相同。仅仅有调用onLayout()后,getWidth()才干获取值。

以下就是推断当前控件是否换行及计算出最大高度和宽度了:

if (lineWidth + childWidth > measureWidth){
     //须要换行
     width = Math.max(lineWidth,width);
     height += lineHeight;
     //因为因为盛不下当前控件。而将此控件调到下一行。所以将此控件的高度和宽度初始化给lineHeight、lineWidth
     lineHeight = childHeight;
     lineWidth = childWidth;
 }else{
     // 否则累加值lineWidth,lineHeight取最大高度
     lineHeight = Math.max(lineHeight,childHeight);
     lineWidth += childWidth;
 }

因为lineWidth是用来累加当前行的总宽度的,所以当lineWidth + childWidth > measureWidth时就表示已经容不下当前这个控件了。这个控件就须要转到下一行;我们先看else部分,即不换行时怎么办?
在不换行时。计算出当前行的最大高度。同一时候将当前子控件的宽度累加到lineWidth上:

lineHeight = Math.max(lineHeight,childHeight);
lineWidth += childWidth;

当须要换行时,首先将当前行宽lineWidth与眼下的最大行宽width比較计算出最新的最大行宽width,作为当前FlowLayout所占的宽度。还要将行高lineHeight累加到height变量上,以便计算出FlowLayout所占的总高度。

width = Math.max(lineWidth,width);
height += lineHeight;

以下就是又一次初始化lineWidth和lineHeight了。因为换行。那当前控件就是下一行控件的第一个控件,那么当前行的行高就是这个控件的高,当前行的行宽就是这个控件的宽度值了:

lineHeight = childHeight;
lineWidth = childWidth;

非常须要注意的是,当计算最后一行时,因为肯定是不会超过行宽的,而我们在for循环中,当不超过行宽中仅仅做了以下处理:

//上面if语句的else部分
 }else{
     // 否则累加值lineWidth,lineHeight取最大高度
     lineHeight = Math.max(lineHeight,childHeight);
     lineWidth += childWidth;
 }

在这里。我们仅仅计算了行宽和行高,但并没有将其width和height做计算,所以,当是最后一行的最后一个控件时,我们要单独运算width、height:

 //最后一行是不会超出width范围的。所以要单独处理
if (i == count -1){
    height += lineHeight;
    width = Math.max(width,lineWidth);
}

(3)最后,通过setMeasuredDimension()设置到系统中:

setMeasuredDimension((measureWidthMode == MeasureSpec.EXACTLY) ? measureWidth
        : width, (measureHeightMode == MeasureSpec.EXACTLY) ? measureHeight
        : height);

完整的代码例如以下:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   super.onMeasure(widthMeasureSpec, heightMeasureSpec);
   int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
   int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
   int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
   int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);

   int lineWidth = 0;
   int lineHeight = 0;
   int height = 0;
   int width = 0;
   int count = getChildCount();
   for (int i=0;i<count;i++){
       View child = getChildAt(i);
       measureChild(child,widthMeasureSpec,heightMeasureSpec);

       MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
       int childWidth = child.getMeasuredWidth() + lp.leftMargin +lp.rightMargin;
       int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

       if (lineWidth + childWidth > measureWidth){
           //须要换行
           width = Math.max(lineWidth,width);
           height += lineHeight;
           //因为因为盛不下当前控件,而将此控件调到下一行,所以将此控件的高度和宽度初始化给lineHeight、lineWidth
           lineHeight = childHeight;
           lineWidth = childWidth;
       }else{
           // 否则累加值lineWidth,lineHeight取最大高度
           lineHeight = Math.max(lineHeight,childHeight);
           lineWidth += childWidth;
       }

       //最后一行是不会超出width范围的,所以要单独处理
       if (i == count -1){
           height += lineHeight;
           width = Math.max(width,lineWidth);
       }

   }
   //当属性是MeasureSpec.EXACTLY时,那么它的高度就是确定的,
   // 仅仅有当是wrap_content时。依据内部控件的大小来确定它的大小时。大小是不确定的,属性是AT_MOST,此时,就须要我们自己计算它的应当的大小,并设置进去
   setMeasuredDimension((measureWidthMode == MeasureSpec.EXACTLY) ?

measureWidth
           : width, (measureHeightMode == MeasureSpec.EXACTLY) ?

measureHeight
           : height);
}

3、重写onLayout()——布局全部子控件

在onLayout()中就是一个个布局子控件了,因为控件要后移和换行,所以我们要标记当前控件的left坐标和top坐标,所以我们要先申请以下几个变量:

protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int count = getChildCount();
    int lineWidth = 0;//累加当前行的行宽
    int lineHeight = 0;//当前行的行高
    int top=0,left=0;//当前坐标的top坐标和left坐标
    ………………
}

然后就是计算每一个控件的top坐标和left坐标,然后调用layout(int left,int top,int right,int bottom)来布局每一个子控件,代码例如以下:(先列出来全部代码。然后再细讲)

for (int i=0; i<count;i++){
    View child = getChildAt(i);
    MarginLayoutParams lp = (MarginLayoutParams) child
            .getLayoutParams();
    int childWidth = child.getMeasuredWidth()+lp.leftMargin+lp.rightMargin;
    int childHeight = child.getMeasuredHeight()+lp.topMargin+lp.bottomMargin;

    if (childWidth + lineWidth >getMeasuredWidth()){
        //假设换行
        top += lineHeight;
        left = 0;
        lineHeight = childHeight;
        lineWidth = childWidth;
    }else{
        lineHeight = Math.max(lineHeight,childHeight);
        lineWidth += childWidth;
    }
    //计算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置为下一子控件的起始点
    left+=childWidth;
}

(1)首先,与onMeasure()一样,先计算出当前孩子的宽和高:

View child = getChildAt(i);
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidth = child.getMeasuredWidth()+lp.leftMargin+lp.rightMargin;
int childHeight = child.getMeasuredHeight()+lp.topMargin+lp.bottomMargin;

(2)然后依据是否要换行来计算当行控件的top坐标和left坐标:

if (childWidth + lineWidth >getMeasuredWidth()){
    //假设换行,当前控件将跑到下一行。从最左边開始。所以left就是0,而top则须要加上上一行的行高。才是这个控件的top点;
    top += lineHeight;
    left = 0;
     //相同。又一次初始化lineHeight和lineWidth
    lineHeight = childHeight;
    lineWidth = childWidth;
}else{
    // 否则累加值lineWidth,lineHeight取最大高度
    lineHeight = Math.max(lineHeight,childHeight);
    lineWidth += childWidth;
}

在计算好left,top之后。然后分别计算出控件应该布局的上、下、左、右四个点坐标:
须要非常注意的是margin不是padding,margin的距离是不绘制的控件内部的,而是控件间的间隔!

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);

最后。计算下一坐标的位置:因为在换行时才会变更top坐标。所以在一个控件绘制结束时,仅仅须要变更left坐标就可以:

//将left置为下一子控件的起始点
left+=childWidth;

到这里就结束了。onLayout的完整代码例如以下:

protected void onLayout(boolean changed, int l, int t, int r, int b) {
   int count = getChildCount();
   int lineWidth = 0;
   int lineHeight = 0;
   int top=0,left=0;
   for (int i=0; i<count;i++){
       View child = getChildAt(i);
       MarginLayoutParams lp = (MarginLayoutParams) child
               .getLayoutParams();
       int childWidth = child.getMeasuredWidth()+lp.leftMargin+lp.rightMargin;
       int childHeight = child.getMeasuredHeight()+lp.topMargin+lp.bottomMargin;

       if (childWidth + lineWidth >getMeasuredWidth()){
           //假设换行,当前控件将跑到下一行,从最左边開始,所以left就是0,而top则须要加上上一行的行高,才是这个控件的top点;
           top += lineHeight;
           left = 0;
           //相同。又一次初始化lineHeight和lineWidth
           lineHeight = childHeight;
           lineWidth = childWidth;
       }else{
           lineHeight = Math.max(lineHeight,childHeight);
           lineWidth += childWidth;
       }
       //计算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置为下一子控件的起始点
       left+=childWidth;
   }

}

好啦,有关FlowLayout的系列文章到这里就结束了,这里主要涉及到ViewGroup的绘制流程的相关知识。希望大家能掌握。

这篇文章感觉有点乱。难度倒是不大,凡是跟代码有关的东东总是非常难驾驭。可能还是语文不行啊,大家见量,多看看源代码吧,理解了上一篇之后,这篇难度不大。

源代码在文章底部给出

參考文章:

1、《Android学习笔记]View的measure过程学习》

2、《Android中measure过程、WRAP_CONTENT具体解释以及xml布局文件解析流程浅析(下)》

3、《【Android】ViewGroup全面分析》

4、《安卓冷知识:LayoutParams》

5、《MeasureSpec介绍及使用具体解释》

6、《Android 自己定义ViewGroup 实战篇 -> 实现FlowLayout》

7、《Android中View绘制流程以及invalidate()等相关方法分析》

8、《android中onMeasure初看,深入理解布局之中的一个!》

9、《MeasureSpec中的測量模式和match_parent、wrap_content是什么相应关系?》

10、《Android视图绘制流程全然解析,带你一步步深入了解View(二)》

11、《通过重写ViewGroup学习onMeasure()和onLayout()方法》

12、《Android开发实践:自己定义ViewGroup的onLayout()分析》

假设本文有帮到你。记得加关注哦

源代码下载地址:http://download.csdn.net/detail/harvic880925/8928371

请大家尊重原创者版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/47035455 ?,谢谢

原文地址:https://www.cnblogs.com/llguanli/p/8641547.html

时间: 2024-07-29 10:58:18

自己定义控件三部曲视图篇(二)——FlowLayout自适应容器实现的相关文章

自己定义控件三部曲视图篇(一)——測量与布局

前言:生命总是要有信仰,有梦想才干一直前行.哪怕走的再慢,也是在前行. 相关文章: <Android自己定义控件三部曲文章索引>:http://blog.csdn.net/harvic880925/article/details/50995268 今天给大家讲讲有关自己定义布局控件的问题,大家来看这样一个需求,你须要设计一个container,实现内部控件自己主动换行.即里面的控件能够依据长度来推断当前行是否容得下它,进而决定是否转到下一行显示.效果图例如以下 在上图中,全部的紫色部分是Flo

Android 自己定义控件开发入门(二)

上一次我们讲了一堆实现自己定义控件的理论基础.列举了View类一些能够重写的方法,我们对这些方法的重写是我们继承View类来派生自己定义控件的关键 我通过一个最简单的样例给大家展示了这一个过程,不管是多么复杂的自己定义控件.思路总是这样子的,可是由于我们只重写了onDraw方法使得大家认为怪怪的.作为一个控件,我们竟然还要为了他的实现为其添加麻烦的监听,这就不能叫做控件了. 以下再给大家介绍一个常常重写的方法法:publicboolean onTouchEvent (MotionEvent ev

自定义控件三部曲视图篇(三)——瀑布流容器WaterFallLayout实现

前言:只要在前行,梦想就不再遥远 系列文章: Android自定义控件三部曲文章索引:http://blog.csdn.net/harvic880925/article/details/50995268 前面两节讲解了有关ViewGroup的onMeasure.onLayout的知识,这节我们深入性地探讨一下,如何实现经常见到的瀑布流容器,本节将实现的效果图如下: 从效果图中可以看出这里要完成的几个功能: 1.图片随机添加 2.在添加图片时,总是将新图片插入到当前最短的列中 3.每个Item后,

Android自己定义控件:进度条的四种实现方式

前三种实现方式代码出自: http://stormzhang.com/openandroid/2013/11/15/android-custom-loading/ (源代码下载)http://download.csdn.net/detail/chaoyu168/9616035 近期一直在学习自己定义控件,搜了很多大牛们Blog里分享的小教程.也上GitHub找了一些类似的控件进行学习.发现读起来都不太好懂,就想写这么一篇东西作为学习笔记吧. 一.控件介绍: 进度条在App中非经常见,比例如以下载

翻翻git之---实现QQ空间点赞部分实现的自己定义控件 EasyLikeArea

转载请注明出处:王亟亟的大牛之路 昨天在家里弄鱼的事没上班,也就没写东西.决定今天早上补一篇,正好看到了 Easy like area in the circle of friends or QQ qzone (?>﹏<?) 这个标题,就下了下代码研习一下.认为不错就分享给大家. 效果图:(这熟悉的icon,大家一目了然,干妹子的作者那位,名字叫啥我还真叫不出抱歉哈.) 作者git:https://github.com/CaMnter 效果非常明显,假设你想在自己的项目中要相似的效果,Easy

git-osc自己定义控件之:CircleImageView

git-osc自己定义控件之:CircleImageView 一.CircleImageView的使用 在项目中能够发现,用户的头像都是圆形的.感觉非常好奇,昨天最终发现了,原来是自定了一个ImageView.先学习下怎样使用,使用过程例如以下: 创建属性文件:attrs.xml,创建路径为-- res/values/attrs.xml .格式例如以下: <?xml version="1.0" encoding="utf-8"?> <resourc

Android自己定义控件之轮播图控件

背景 近期要做一个轮播图的效果.网上看了几篇文章.基本上都能找到实现,效果还挺不错,可是在写的时候感觉每次都要单独去又一次在Activity里写一堆代码.于是自己封装了一下.这里仅仅是做了下封装成一个控件,不必每次反复写代码了. 效果图 实现分析 轮播图的功能就是实现左右滑动的广告.图片信息展示,那我们就用ViewPager来实现,由于考虑到用户体验,我们还须要在以下加一个指示器来标示滑动到了第几张轮播图.指示器我们能够用一个线性布局来依据要展示的轮播图设置显示的View,我们要做这种一个控件没

从源码中浅析Android中如何利用attrs和styles定义控件

一直有个问题就是,Android中是如何通过布局文件,就能实现控件效果的不同呢?比如在布局文件中,我设置了一个TextView,给它设置了textColor,它就能够改变这个TextView的文本的颜色.这是如何做到的呢?我们分3个部分来看这个问题1.attrs.xml  2.styles.xml  3.看组件的源码. 1.attrs.xml: 我们知道Android的源码中有attrs.xml这个文件,这个文件实际上定义了所有的控件的属性,就是我们在布局文件中设置的各类属性 你可以找到attr

android 自己定义控件属性(TypedArray以及attrs解释)

近期在捣鼓android 自己定义控件属性,学到了TypedArray以及attrs.在这当中看了一篇大神博客Android 深入理解Android中的自己定义属性.我就更加深入学习力一番.我就沿着这个学习,讲一下流程吧,兴许一篇还有应用. 1.attrs文件编写 <?xml version="1.0" encoding="utf-8"?> <resources> <attr name="titleText" for