編輯:關於 Android 程式設計
在多數 App 裡都見過「熱門標籤」那種會自動換行的流式布局。本文就來動手做一個類似效果的熱門標籤版面(源碼附在最後)。
原理圖:

特點:當上一行剩餘空間不足以容納新的 TextView 時,才另起一行。
場景:主要用於關鍵詞搜尋、熱門標籤這類需要不定數量、不定長度項目自動排列的地方。
(1)onMeasure:測量子 View 的寬高,並決定自己的寬高。做法是依子 View 在布局檔中的屬性給定測量模式與測量值。
測量結果 = 測量模式 + 測量值,模式共三種:
EXACTLY:父容器已確定精確尺寸。子 View 設為明確數值或 match_parent 時通常對應此模式。
AT_MOST:子 View 尺寸被限制在一個最大值內,對應 wrap_content。
UNSPECIFIED:子 View 想要多大就多大,常見於 AdapterView 的 item 或 ScrollView 的子 View,實際上比較少見。
(2)onLayout:決定每個子 View 的最終位置。
每個 ViewGroup 對應一個 LayoutParams,也就是 ViewGroup → LayoutParams 的關係。不確定 getLayoutParams() 會拿到哪一種時,記住一個規則就好:子 View 取到的 LayoutParams,就是其父容器的 LayoutParams。例如 LinearLayout 中的子 View 取到的是 LinearLayout.LayoutParams。
因此我們的 FlowLayout 也需要自己的 LayoutParams。由於範例中的效果用到子 View 的 margin,這裡應該使用 MarginLayoutParams,即 FlowLayout → MarginLayoutParams。

依上述分析,讓類別繼承 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); } }
引用自訂控制項:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://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_bg.xml):
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="https://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); } } }
順手再附上一份寫法更精簡、並補上自身 marginTop/marginLeft 支援的版本:
// 流式布局 話不多說,比較簡單,注釋都寫的很清楚 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 Mr.Himan * @version 1.0<br> * 2015年11月4日 11:12:06 <br> * 流式布局 設置MarginTop 和MarginLeft有效 MarginRight 暫未實現 */ public class FlowLayout extends ViewGroup { /** * 存儲所有的子View */ private List<List<View>> mAllChildViews = new ArrayList<List<View>>(); /** * 存儲每一行的高度 */ private List<Integer> mLineHeight = new ArrayList<Integer>(); public FlowLayout(Context context) { this(context, null); } public FlowLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FlowLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { 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); MarginLayoutParams params = (MarginLayoutParams) this.getLayoutParams(); // 設置子View的位置 int left = 0; // 添加marginTop int top = 0 + params.topMargin; // 獲取行數 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++) { // 為每一列設置marginLeft if (j == 0) { left = 0 + params.leftMargin; } 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; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 父控件傳進來的寬度和高度以及對應的測量模式 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 params = (MarginLayoutParams) child .getLayoutParams(); // 子View占據的寬度 int childWidth = child.getMeasuredWidth() + params.leftMargin + params.rightMargin; // 子View占據的高度 int childHeight = child.getMeasuredHeight() + params.bottomMargin + params.topMargin; // 換行時候 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; } } setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width, modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height); } /** * 與當前ViewGroup對應的LayoutParams */ @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } }
兩份實作的核心思路一致:用兩個集合分別記錄「每一行有哪些子 View」與「每一行的高度」,onMeasure 負責算出整體尺寸,onLayout 負責把子 View 擺到正確座標。差別只在第二份額外處理了容器自身的 margin,且沒有覆寫 generateLayoutParams(因此 margin 需另外設定)。
以上就是本文的全部內容,希望對大家學習 Android 流式布局有所幫助。
Android 緩存機制深度解析:LruCache、DiskLruCache 與二級緩存實踐
一、先推薦一個輕量級方案:ACache ACache(ASimpleCache)的用法與 SharedPreferences 類似,但容量更強。SharedPrefere
Android 自定義 View 繪製完全手冊:Paint、Canvas、Path 與 PathMeasure
這篇拖了很久的文章,算是對自己上半年的一個交代。起因是有朋友希望整理一份 Android Canvas 的相關總結,結果一放就放掉了;最近又有人催更,於是就有了這篇「超級
Android 自定義控件屬性與刮刮樂:打碼、保存圖片完整實作
這個 Demo 整合自定義 View、自定義屬性與圖形處理,可作為刮刮樂、圖片打碼與圖片保存的綜合練習。 自定義屬性 在 res/values 建立 declare-s
Android 實現藍牙檔案發送,兼容多種機型
最近專案上需要實現一個透過藍牙傳輸 apk 的功能,能夠搜尋周邊的藍牙手機並分享檔案。從需求來看,Android 手機自帶的藍牙傳輸模組其實就能滿足,實現起來也很簡單。但