android流式布局

image

一、概述:
在日常的app使用中,我们会在android 的app中看见 热门标签等自动换行的流式布局,今天,我们就来看看如何

自定义一个类似热门标签那样的流式布局吧(源码下载在下面最后给出)

类似的自定义布局。下面我们就来详细介绍流式布局的应用特点以及用的的技术点:

1.流式布局的特点以及应用场景

特点:当上面一行的空间不够容纳新的TextView时候,
才开辟下一行的空间

原理图:


image
场景:主要用于关键词搜索或者热门标签等场景

2.自定义ViewGroup,重点重写下面两个方法

1、onMeasure:测量子view的宽高,设置自己的宽和高
2、onLayout:设置子view的位置
onMeasure:根据子view的布局文件中属性,来为子view设置测量模式和测量值
测量=测量模式+测量值;

测量模式有3种:
EXACTLY:表示设置了精确的值,一般当childView设置其宽、高为精确值、match_parent时,ViewGroup会将其设置为EXACTLY;
AT_MOST:表示子布局被限制在一个最大值内,一般当childView设置其宽、高为wrap_content时,ViewGroup会将其设置为AT_MOST;
UNSPECIFIED:表示子布局想要多大就多大,一般出现在AadapterView的item的heightMode中、ScrollView的childView的heightMode中;此种模式比较少见。

3.LayoutParams

ViewGroup LayoutParams :每个 ViewGroup 对应一个 LayoutParams; 即 ViewGroup -> LayoutParams
getLayoutParams 不知道转为哪个对应的LayoutParams ,其实很简单,就是如下:
子View.getLayoutParams 得到的LayoutParams对应的就是 子View所在的父控件的LayoutParams;
例如,LinearLayout 里面的子view.getLayoutParams ->LinearLayout.LayoutParams
所以 咱们的FlowLayout 也需要一个LayoutParams,由于上面的效果图是子View的 margin,
所以应该使用MarginLayoutParams。即FlowLayout->MarginLayoutParams

二、热门标签的流式布局的实现:

  1. 自定义热门标签的ViewGroup实现

根据上面的技术分析,自定义类继承于ViewGroup,并重写 onMeasure和onLayout等方法。具体实现代码如下:

  package com.czm.flowlayout;  

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

  import android.content.Context;  
  import android.util.AttributeSet;  
  import android.view.View;  
  import android.view.ViewGroup;  
  /**  
   *   
   * @author caizhiming  
   * @created on 2015-4-13  
   */  
   public class XCFlowLayout extends ViewGroup{  

//存储所有子View  
private List<List<View>> mAllChildViews = new ArrayList<>();  
//每一行的高度  
private List<Integer> mLineHeight = new ArrayList<>();  
  
public XCFlowLayout(Context context) {  
    this(context, null);  
    // TODO Auto-generated constructor stub  
}  
public XCFlowLayout(Context context, AttributeSet attrs) {  
    this(context, attrs, 0);  
    // TODO Auto-generated constructor stub  
}  
public XCFlowLayout(Context context, AttributeSet attrs, int defStyle) {  
    super(context, attrs, defStyle);  
    // TODO Auto-generated constructor stub  
}  
@Override  
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
    // TODO Auto-generated method stub  
      
    //父控件传进来的宽度和高度以及对应的测量模式  
    int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);  
    int modeWidth = MeasureSpec.getMode(widthMeasureSpec);  
    int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);  
    int modeHeight = MeasureSpec.getMode(heightMeasureSpec);  
      
    //如果当前ViewGroup的宽高为wrap_content的情况  
    int width = 0;//自己测量的 宽度  
    int height = 0;//自己测量的高度  
    //记录每一行的宽度和高度  
    int lineWidth = 0;  
    int lineHeight = 0;  
      
    //获取子view的个数  
    int childCount = getChildCount();  
    for(int i = 0;i < childCount; i ++){  
        View child = getChildAt(i);  
        //测量子View的宽和高  
        measureChild(child, widthMeasureSpec, heightMeasureSpec);  
        //得到LayoutParams  
        MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams();  
        //子View占据的宽度  
        int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;  
        //子View占据的高度  
        int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;  
        //换行时候  
        if(lineWidth + childWidth > sizeWidth){  
            //对比得到最大的宽度  
            width = Math.max(width, lineWidth);  
            //重置lineWidth  
            lineWidth = childWidth;  
            //记录行高  
            height += lineHeight;  
            lineHeight = childHeight;  
        }else{//不换行情况  
            //叠加行宽  
            lineWidth += childWidth;  
            //得到最大行高  
            lineHeight = Math.max(lineHeight, childHeight);  
        }  
        //处理最后一个子View的情况  
        if(i == childCount -1){  
            width = Math.max(width, lineWidth);  
            height += lineHeight;  
        }  
    }  
    //wrap_content  
    setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,  
            modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height);  
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
}  
  
@Override  
protected void onLayout(boolean changed, int l, int t, int r, int b) {  
    // TODO Auto-generated method stub  
    mAllChildViews.clear();  
    mLineHeight.clear();  
    //获取当前ViewGroup的宽度  
    int width = getWidth();  
      
    int lineWidth = 0;  
    int lineHeight = 0;  
    //记录当前行的view  
    List<View> lineViews = new ArrayList<View>();  
    int childCount = getChildCount();  
    for(int i = 0;i < childCount; i ++){  
        View child = getChildAt(i);  
        MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();  
        int childWidth = child.getMeasuredWidth();  
        int childHeight = child.getMeasuredHeight();  
          
        //如果需要换行  
        if(childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width){  
            //记录LineHeight  
            mLineHeight.add(lineHeight);  
            //记录当前行的Views  
            mAllChildViews.add(lineViews);  
            //重置行的宽高  
            lineWidth = 0;  
            lineHeight = childHeight + lp.topMargin + lp.bottomMargin;  
            //重置view的集合  
            lineViews = new ArrayList();  
        }  
        lineWidth += childWidth + lp.leftMargin + lp.rightMargin;  
        lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);  
        lineViews.add(child);  
    }  
    //处理最后一行  
    mLineHeight.add(lineHeight);  
    mAllChildViews.add(lineViews);  
      
    //设置子View的位置  
    int left = 0;  
    int top = 0;  
    //获取行数  
    int lineCount = mAllChildViews.size();  
    for(int i = 0; i < lineCount; i ++){  
        //当前行的views和高度  
        lineViews = mAllChildViews.get(i);  
        lineHeight = mLineHeight.get(i);  
        for(int j = 0; j < lineViews.size(); j ++){  
            View child = lineViews.get(j);  
            //判断是否显示  
            if(child.getVisibility() == View.GONE){  
                continue;  
            }  
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();  
            int cLeft = left + lp.leftMargin;  
            int cTop = top + lp.topMargin;  
            int cRight = cLeft + child.getMeasuredWidth();  
            int cBottom = cTop + child.getMeasuredHeight();  
            //进行子View进行布局  
            child.layout(cLeft, cTop, cRight, cBottom);  
            left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;  
        }  
        left = 0;  
        top += lineHeight;  
    }  
      
}  
/**  
 * 与当前ViewGroup对应的LayoutParams  
 */  
@Override  
public LayoutParams generateLayoutParams(AttributeSet attrs) {  
    // TODO Auto-generated method stub  
      
    return new MarginLayoutParams(getContext(), attrs);  
}  
  }  
2.相关的布局文件:

引用自定义控件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools"  
android:id="@+id/container"  
android:layout_width="match_parent"  
android:layout_height="match_parent" >  
<com.czm.flowlayout.XCFlowLayout  
    android:id="@+id/flowlayout"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent" >  
</com.czm.flowlayout.XCFlowLayout>  
</RelativeLayout>  

TextView的样式文件:

 <?xml version="1.0" encoding="utf-8"?>  
<shape xmlns:android="http://schemas.android.com/apk/res/android" >  
<solid android:color="#666666" />  
<corners android:radius="10dp" />  
<padding   
    android:left="5dp"  
    android:right="5dp"  
    android:top="5dp"  
    android:bottom="5dp"   
    />  
   </shape>  

三、使用该自定义布局控件类

最后,如何使用该自定义的热门标签控件类呢?很简单,请看下面实例代码:

        package com.czm.flowlayout;  

        import android.app.Activity;  
        import android.graphics.Color;  
        import android.os.Bundle;  
        import android.view.ViewGroup.LayoutParams;  
        import android.view.ViewGroup.MarginLayoutParams;  
        import android.widget.TextView;  
        /**  
         *   
         * @author caizhiming  
         * @created on 2015-4-13  
         */  
        public class MainActivity extends Activity {  

      private String mNames[] = {  
        "welcome","android","TextView",  
        "apple","jamy","kobe bryant",  
        "jordan","layout","viewgroup",  
        "margin","padding","text",  
        "name","type","search","logcat"  
};  
private XCFlowLayout mFlowLayout;  
@Override  
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_main);  
      
    initChildViews();  
      
}  
private void initChildViews() {  
    // TODO Auto-generated method stub  
    mFlowLayout = (XCFlowLayout) findViewById(R.id.flowlayout);  
    MarginLayoutParams lp = new MarginLayoutParams(  
            LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);  
    lp.leftMargin = 5;  
    lp.rightMargin = 5;  
    lp.topMargin = 5;  
    lp.bottomMargin = 5;  
    for(int i = 0; i < mNames.length; i ++){  
        TextView view = new TextView(this);  
        view.setText(mNames[i]);  
        view.setTextColor(Color.WHITE);  
        view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_bg));  
        mFlowLayout.addView(view,lp);  
    }  
}  

  }  
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容