自訂流式布局,自訂布局

來源:互聯網
上載者:User

自訂流式布局,自訂布局
1、概述

何為FlowLayout,就是控制項根據ViewGroup的寬,自動的往右添加,如果當前行剩餘空間不足,則自動添加到下一行。有點所有的控制項都往左飄的感覺,第一行滿了,往第二行飄~所以也叫流式布局。Android並沒有提供流式布局,但是某些場合中,流式布局還是非常適合使用的,比如關鍵字標籤,搜尋熱詞列表等,比如:

這些都特別適合使用FlowLayout

2、簡單的分析

1、對於FlowLayout,需要指定的LayoutParams,我們目前只需要能夠識別margin即可,即使用MarginLayoutParams.

2、onMeasure中計算所有childView的寬和高,然後根據childView的寬和高,計算自己的寬和高。(當然,如果不是wrap_content,直接使用父ViewGroup傳入的計算值即可)

3、onLayout中對所有的childView進行布局。

  1 package com.gcp;  2   3 import android.content.Context;  4 import android.util.AttributeSet;  5 import android.util.Log;  6 import android.view.View;  7 import android.view.ViewGroup;  8   9 import java.util.ArrayList; 10 import java.util.List; 11  12 public class FlowLayout extends ViewGroup { 13     public FlowLayout(Context context) { 14         this(context, null); 15     } 16  17     public FlowLayout(Context context, AttributeSet attrs) { 18         this(context, attrs, 0); 19     } 20  21     public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) { 22         super(context, attrs, defStyleAttr); 23  24     } 25  26     //能夠設定當前布局的寬度和高度 27     @Override 28     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 29 //        super.onMeasure(widthMeasureSpec, heightMeasureSpec); 30         //擷取設定的寬高的模式和具體的值 31         int widthMode = MeasureSpec.getMode(widthMeasureSpec); 32         int heightMode = MeasureSpec.getMode(heightMeasureSpec); 33         int widthSize = MeasureSpec.getSize(widthMeasureSpec); 34         int heightSize = MeasureSpec.getSize(heightMeasureSpec); 35  36         //如果使用者使用的至多模式,那麼使用如下兩個變數計算真實的寬高值。 37         int width = 0; 38         int height = 0; 39  40         //每一行的寬度 41         int lineWidth = 0; 42         int lineHeight = 0; 43  44         //擷取子視圖 45         int childCount = getChildCount(); 46         for (int i = 0; i < childCount; i++) { 47             View childView = getChildAt(i); 48  49             //只有調用了如下的方法,方可計運算元視圖的測量的寬高 50             measureChild(childView, widthMeasureSpec, heightMeasureSpec); 51  52             //擷取子視圖的寬高 53             int childWidth = childView.getMeasuredWidth(); 54             int childHeight = childView.getMeasuredHeight(); 55             //要想保證可以擷取子視圖的邊距參數對象,必須重寫generateLayoutParams(). 56             MarginLayoutParams mp = (MarginLayoutParams) childView.getLayoutParams(); 57  58             if (lineWidth + childWidth + mp.leftMargin + mp.rightMargin <= widthSize){//不換行 59  60                 lineWidth += childWidth + mp.leftMargin + mp.rightMargin; 61                 lineHeight = Math.max(lineHeight,childHeight + mp.topMargin + mp.bottomMargin); 62  63             }else{//換行 64                 width = Math.max(width,lineWidth); 65                 height += lineHeight; 66  67                 //重設 68                 lineWidth = childWidth + mp.leftMargin + mp.rightMargin; 69                 lineHeight = childHeight + mp.topMargin + mp.bottomMargin; 70             } 71  72             //最後一個元素 73             if(i == childCount - 1){ 74                 width = Math.max(width,lineWidth); 75                 height += lineHeight; 76             } 77  78         } 79  80         Log.e("TAG", "widthSize = " + widthSize + ",heightSize = " + heightSize); 81         Log.e("TAG", "width = " + width + ",height = " + height); 82  83  84         //設定當前流式布局的寬高 85         setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? widthSize : width, (heightMode == MeasureSpec.EXACTLY) ? heightSize : height); 86     } 87  88     //重寫的目的:給每一個子視圖指定顯示的位置:childView.layout(l,t,r,b); 89     private List<List<View>> allViews = new ArrayList<>();//每一行的子視圖的集合構成的集合。 90     private List<Integer> allHeights = new ArrayList<>();//每一行的高度構成的集合。 91     @Override 92     protected void onLayout(boolean changed, int l, int t, int r, int b) { 93         //一、給兩個集合添加元素。 94  95         //每一行的寬高值 96         int lineWidth = 0; 97         int lineHeight = 0; 98  99         //提供一個集合,儲存一行childView100         List<View> lineList = new ArrayList<>();101         //擷取布局的寬度102         int width = this.getMeasuredWidth();103 104         int childCount = getChildCount();105         for(int i = 0; i < childCount; i++) {106             View childView = getChildAt(i);107             //擷取視圖的測量寬高、邊距108             int childWidth = childView.getMeasuredWidth();109             int childHeight = childView.getMeasuredHeight();110 111             MarginLayoutParams mp = (MarginLayoutParams) childView.getLayoutParams();112 113             if(lineWidth + childWidth + mp.leftMargin + mp.rightMargin <= width){//不換行114                 lineList.add(childView);115                 lineWidth += childWidth + mp.leftMargin + mp.rightMargin;116                 lineHeight = Math.max(lineHeight,childHeight + mp.topMargin + mp.bottomMargin);117 118             }else{//換行119                 allViews.add(lineList);120                 allHeights.add(lineHeight);121 122                 lineWidth = childWidth + mp.leftMargin + mp.rightMargin;123                 lineHeight = childHeight + mp.topMargin + mp.bottomMargin;124                 lineList = new ArrayList<>();125                 lineList.add(childView);126             }127 128             if(i == childCount - 1){//如果是最後一個元素129                 allViews.add(lineList);130                 allHeights.add(lineHeight);131             }132 133         }134 135         Log.e("TAG", "allViews.size = " + allViews.size() + ",allHeights.size = " + allHeights.size());136 137         //二、給每一個子視圖指定顯示的位置138         int x = 0;139         int y = 0;140         for(int i = 0; i < allViews.size(); i++) {//每遍曆一次,對應一行元素141             List<View> lineViews = allViews.get(i);//取出當前行構成的集合142             for(int j = 0; j < lineViews.size(); j++) {143                 View childView = lineViews.get(j);144                 int childWidth = childView.getMeasuredWidth();145                 int childHeight = childView.getMeasuredHeight();146 147                 MarginLayoutParams mp = (MarginLayoutParams) childView.getLayoutParams();148 149                 int left = x + mp.leftMargin;150                 int top = y + mp.topMargin;151                 int right = left + childWidth;152                 int bottom = top + childHeight;153 154                 childView.layout(left,top,right,bottom);155 156                 x +=  childWidth + mp.leftMargin + mp.rightMargin;157 158             }159             y += allHeights.get(i);160             x = 0;161         }162     }163 164     @Override165     public LayoutParams generateLayoutParams(AttributeSet attrs) {166         MarginLayoutParams mp = new MarginLayoutParams(getContext(), attrs);167         return mp;168 169     }170 }
FlowLayout

 

3、generateLayoutParams

因為我們只需要支援margin,所以直接使用系統的MarginLayoutParams

@Override  public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)  {      return new MarginLayoutParams(getContext(), attrs);  }  
4、onMeasure

  首先得到其父容器傳入的測量模式和寬高的計算值,然後遍曆所有的childView,使用measureChild方法對所有的childView進行測量。然後根據所有childView的測量得出的寬和高得到該ViewGroup如果設定為wrap_content時的寬和高。最後根據模式,如果是MeasureSpec.EXACTLY則直接使用父ViewGroup傳入的寬和高,否則設定為自己計算的寬和高。

5、onLayout

onLayout中完成對所有childView的位置以及大小的指定

6、測試

我準備使用TextView作為我們的標籤,所以為其簡單寫了一點樣式:

res/values/styles.xml中:

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

flag_01.xml

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

布局檔案:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      android:background="#E1E6F6"      android:orientation="vertical" >        <com.gcp.FlowLayout          android:layout_width="fill_parent"          android:layout_height="wrap_content" >            <TextView              style="@style/text_flag_01"              android:text="Welcome" />            <TextView              style="@style/text_flag_01"              android:text="IT工程師" />            <TextView              style="@style/text_flag_01"              android:text="學習ing" />            <TextView              style="@style/text_flag_01"              android:text="戀愛ing" />            <TextView              style="@style/text_flag_01"              android:text="掙錢ing" />            <TextView              style="@style/text_flag_01"              android:text="努力ing" />            <TextView              style="@style/text_flag_01"              android:text="I thick i can" />      </com.gcp.FlowLayout>            </LinearLayout>  

:

  

參考:

http://blog.csdn.net/jdsjlzx/article/details/45042081?ref=myread

http://blog.csdn.net/lmj623565791/article/details/38352503/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.