編輯:關於 Android 程式設計
在 Android 開發裡,我們時常會遇到「流式」的版面需求,最常見的就是標籤的排列顯示——例如 QQ 的個人標籤、搜尋框下方的提示詞,都是典型的流式版面。今天就把日常開發中碰到的流式版面做個整理與歸納。
源碼下載地址:https://github.com/gdutxiaoxu/CustomViewDemo.git

圖一

圖二

仔細對比可以發現,圖二其實是圖一的進化版。圖一在元件寬度超過一行時,剩下的空間不會自動分配給每個元件;而圖二在換行時,若元件尚未填滿整行,會自動把剩餘寬度平均攤到每個元件上。
` /** * 博客地址:https://blog.csdn.net/gdutxiaoxu * @author xujun * @time 2016/6/20 23:49. */ public class SimpleFlowLayout extends ViewGroup { private int verticalSpacing = 20; public SimpleFlowLayout(Context context ) { super(context); } /** * 重寫onMeasure方法是為了確定最終的大小 * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); //處理Padding屬性,讓當前的ViewGroup支持Padding int widthUsed = paddingLeft + paddingRight; int heightUsed = paddingTop + paddingBottom; int childMaxHeightOfThisLine = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { // 已用的寬度 int childUsedWidth = 0; // 已用的高度 int childUsedHeight = 0; // 調用ViewGroup自身的方法測量孩子的寬度和高度,我們也可以自己根據MeasureMode來測量 measureChild(child,widthMeasureSpec,heightMeasureSpec); childUsedWidth += child.getMeasuredWidth(); childUsedHeight += child.getMeasuredHeight(); //處理Margin,支持孩子的Margin屬性 Rect marginRect = getMarginRect(child); int leftMargin=marginRect.left; int rightMargin=marginRect.right; int topMargin=marginRect.top; int bottomMargin=marginRect.bottom; childUsedWidth += leftMargin + rightMargin; childUsedHeight += topMargin + bottomMargin; //總寬度沒有超過本行 if (widthUsed + childUsedWidth < widthSpecSize) { widthUsed += childUsedWidth; if (childUsedHeight > childMaxHeightOfThisLine) { childMaxHeightOfThisLine = childUsedHeight; } } else {//總寬度已經超過本行 heightUsed += childMaxHeightOfThisLine + verticalSpacing; widthUsed = paddingLeft + paddingRight + childUsedWidth; childMaxHeightOfThisLine = childUsedHeight; } } } //加上最後一行的最大高度 heightUsed += childMaxHeightOfThisLine; setMeasuredDimension(widthSpecSize, heightUsed); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); /** * 為了 支持Padding屬性 */ int childStartLayoutX = paddingLeft; int childStartLayoutY = paddingTop; int widthUsed = paddingLeft + paddingRight; int childMaxHeight = 0; int childCount = getChildCount(); //擺放每一個孩子的高度 for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childNeededWidth, childNeedHeight; int left, top, right, bottom; int childMeasuredWidth = child.getMeasuredWidth(); int childMeasuredHeight = child.getMeasuredHeight(); Rect marginRect = getMarginRect(child); int leftMargin=marginRect.left; int rightMargin=marginRect.right; int topMargin=marginRect.top; int bottomMargin=marginRect.bottom; childNeededWidth = leftMargin + rightMargin + childMeasuredWidth; childNeedHeight = topMargin + topMargin + childMeasuredHeight; // 沒有超過本行 if (widthUsed + childNeededWidth <= r - l) { if (childNeedHeight > childMaxHeight) { childMaxHeight = childNeedHeight; } left = childStartLayoutX + leftMargin; top = childStartLayoutY + topMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; } else { childStartLayoutY += childMaxHeight + verticalSpacing; childStartLayoutX = paddingLeft; widthUsed = paddingLeft + paddingRight; left = childStartLayoutX + leftMargin; top = childStartLayoutY + topMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; childMaxHeight = childNeedHeight; } child.layout(left, top, right, bottom); } } } private Rect getMarginRect(View child) { LayoutParams layoutParams = child.getLayoutParams(); int leftMargin = 0; int rightMargin = 0; int topMargin = 0; int bottomMargin = 0; if (layoutParams instanceof MarginLayoutParams) { MarginLayoutParams marginLayoutParams = (MarginLayoutParams) layoutParams; leftMargin = marginLayoutParams.leftMargin; rightMargin = marginLayoutParams.rightMargin; topMargin = marginLayoutParams.topMargin; bottomMargin = marginLayoutParams.bottomMargin; } return new Rect(leftMargin, topMargin, rightMargin, bottomMargin); } }`
首先重寫 onMeasure(),在其中呼叫 measureChild() 取得每個子元件的寬高。每加入一個孩子就執行 widthUsed += childUsedWidth;,累加已用寬度。
加完一個孩子後,判斷 widthUsed 是否超出元件本身的最大寬度 widthSpecSize。若沒超過,就執行:
widthUsed += childUsedWidth; if (childUsedHeight > childMaxHeightOfThisLine) { childMaxHeightOfThisLine = childUsedHeight; }
若超過了,就換行:
heightUsed += childMaxHeightOfThisLine + verticalSpacing; widthUsed = paddingLeft + paddingRight + childUsedWidth; childMaxHeightOfThisLine = childUsedHeight;
最後呼叫 setMeasuredDimension(widthSpecSize, heightUsed); 設定它的大小。
3. 在 onLayout() 裡,工作則是擺放每個孩子的位置:判斷需不需要換行——不需要換行就只改 left 值,需要換行就改 top 值。
動手之前,先補一個基礎知識。

從這張圖可以歸納出:
Width = 元件真正的寬度(realWidth)+ PaddingLeft + PaddingRight;margin 則是子元件相對於父元件的距離。
注意事項
為了讓版面支持 padding,我們一開始就把 padding 計入已用寬高:
int widthUsed = paddingLeft + paddingRight; int heightUsed = paddingTop + paddingBottom; ---------- if (widthUsed + childUsedWidth < widthSpecSize) { widthUsed += childUsedWidth; if (childUsedHeight > childMaxHeightOfThisLine) { childMaxHeightOfThisLine = childUsedHeight; } }
而為了支持子元件的 margin,我們也做了對應處理:
Rect marginRect = getMarginRect(child); int leftMargin=marginRect.left; int rightMargin=marginRect.right; int topMargin=marginRect.top; int bottomMargin=marginRect.bottom; childUsedWidth += leftMargin + rightMargin; childUsedHeight += topMargin + bottomMargin;
也就是說,在計算孩子占用的寬高時把 margin 加進去,在統計整行總寬高時再把每個孩子的 margin 一并算入,這樣自然就支持了子元件的 margin 屬性。
如圖所示,當元件寬度參差不齊時,換行後會在行尾留下一些剩餘寬度。對於追求健壯程式碼的我們來說,總覺得有點彆扭,於是我們想到了改進辦法。

解決方案見下。

/** * 博客地址:https://blog.csdn.net/gdutxiaoxu * @author xujun * @time 2016/6/26 22:54. */ public class PrefectFlowLayout extends ViewGroup { public PrefectFlowLayout(Context context) { super(context); } public PrefectFlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } public PrefectFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } private int parentWidthSize;//父容器寬度 private int horizontalSpacing = 16;//水平間距 private int verticalSpacing = 16;//垂直間距 private Line currentLine;//當前行 private List mLines = new ArrayList<>();//所有行的集合 private int userWidth = 0;//當前行已使用寬度 /** * 行對象 */ private class Line { private List children;//一行裡面所添加的子View集合 private int height;//當前行高度 private int lineWidth = 0;//當前行已使用寬度 public Line() { children = new ArrayList<>(); } /** * 添加一個子控件 * * @param child */ private void addChild(View child) { children.add(child); if (child.getMeasuredHeight() > height) { height = child.getMeasuredHeight();//當前行高度以子控件最大高度為准 } lineWidth += child.getMeasuredWidth();//將每個子控件寬度進行累加,記錄使用的寬度 } /** * 獲取行的高度 * * @return */ public int getHeight() { return height; } /** * 獲取子控件的數量 * * @return */ public int getChildCount() { return children.size(); } /** * 放置每一行裡面的子控件的位置 * * @param l 距離最左邊的距離 * @param t 距離最頂端的距離 */ public void onLayout(int l, int t) { //當前行使用的寬度,等於每個子控件寬度之和+子控件之間的水平距離 lineWidth += horizontalSpacing * (children.size() - 1); int surplusChild = 0; int surplus = parentWidthSize - lineWidth;//剩余寬度 if (surplus > 0) { //如果有剩余寬度,則將剩余寬度平分給每一個子控件 surplusChild = (int) (surplus / children.size()+0.5); } for (int i = 0; i < children.size(); i++) { View child = children.get(i); child.getLayoutParams().width=child.getMeasuredWidth()+surplusChild; if (surplusChild>0){//如果長度改變了後,需要重新測量,否則布局中的屬性大小還會是原來的大小 child.measure(MeasureSpec.makeMeasureSpec(child.getMeasuredWidth()+surplusChild,MeasureSpec.EXACTLY) ,MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY)); } child.layout(l, t, l + child.getMeasuredWidth(), t + child.getMeasuredHeight()); l += child.getMeasuredWidth() + horizontalSpacing; } } } // getMeasuredWidth() 控件實際的大小 // getWidth() 控件顯示的大小 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //將之前測量的數據進行清空,以防復用時影響下次測量 mLines.clear(); currentLine = null; userWidth = 0; //獲取父容器的寬度和模式 int widthMode = MeasureSpec.getMode(widthMeasureSpec); parentWidthSize = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); //獲取父容器的高度和模式 int heigthMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); int childWidthMode, childHeightMode; //為了測量每個子控件,需要指定每個子控件的測量規則 //子控件設置為WRAP_CONTENT,具體測量規則詳見,ViewGroup的getChildMeasureSpec()方法 if (widthMode == MeasureSpec.EXACTLY) { childWidthMode = MeasureSpec.AT_MOST; } else { childWidthMode = widthMode; } if (heigthMode == MeasureSpec.EXACTLY) { childHeightMode = MeasureSpec.AT_MOST; } else { childHeightMode = heigthMode; } //獲取到子控件高和寬的測量規則 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(parentWidthSize, childWidthMode); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, childHeightMode); currentLine = new Line();//創建第一行 for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); //測量每一個孩子 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); int childMeasuredWidth = child.getMeasuredWidth();//獲取當前子控件的實際寬度 userWidth += childMeasuredWidth;//讓當前行使用寬度加上當前子控件寬度 if (userWidth <= parentWidthSize) { //如果當前行使用寬度小於父控件的寬度,則加入該行 currentLine.addChild(child); userWidth += horizontalSpacing;//當前行使用寬度加上子控件之間的水平距離 if (userWidth > parentWidthSize) {//如果當前行加上水平距離後超出父控件寬度,則換行 newLine(); } } else { if (currentLine.getChildCount() == 0) {//以防出現一個子控件寬度超過父控件的情況出現 currentLine.addChild(child); } newLine(); currentLine.addChild(child);//並將超出范圍的當前的子控件加入新的行中 userWidth = child.getMeasuredWidth()+horizontalSpacing;//並將使用寬度加上子控件的寬度; } } if (!mLines.contains(currentLine)) {//加入最後一行,因為如果最後一行寬度不足父控件寬度時,就未換行 mLines.add(currentLine); } int totalHeight = 0;//總高度 for (Line line : mLines) { totalHeight += line.getHeight() + verticalSpacing;//總高度等於每一行的高度+垂直間距 } setMeasuredDimension(parentWidthSize + getPaddingLeft() + getPaddingRight(), resolveSize(totalHeight + getPaddingTop() + getPaddingBottom(), heightMeasureSpec));//resolveSize(),將實際高度與父控件高度進行比較,選取最合適的 } /** * 換行 */ private void newLine() { mLines.add(currentLine);//記錄之前行 currentLine = new Line();//重新創建新的行 userWidth = 0;//將使用寬度初始化 } /** * 放置每個子控件的位置 * * @param changed * @param l * @param t * @param r * @param b */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { l += getPaddingLeft(); t += getPaddingTop(); for (int i = 0; i < mLines.size(); i++) { Line line = mLines.get(i); line.onLayout(l, t);//設置每一行的位置,每一行的子控件由其自己去分配 t += line.getHeight() + verticalSpacing;//距離最頂端的距離,即每一行高度和垂直間距的累加 } } /** * 獲取子控件的測量規則 * * @param mode 父控件的測量規則 * @return 子控件設置為WRAP_CONTENT,具體測量規則詳見,ViewGroup的getChildMeasureSpec()方法 */ private int getMode(int mode) { int childMode = 0; if (mode == MeasureSpec.EXACTLY) { childMode = MeasureSpec.AT_MOST; } else { childMode = mode; } return childMode; } }
對比圖一的思路,這次我們封裝了一個 Line 內部類。顧名思義,一個 Line 實例就代表一行,其中的 List children 用來存放孩子:
private List children;//一行裡面所添加的子View集合
Line 裡還封裝了 void onLayout(int l, int t) 方法,讓它自己去拜訪每個孩子的位置,从而实现剩餘寬度的平均分配。核心就在這幾行程式碼:
if (surplus > 0) { //如果有剩余寬度,則將剩余寬度平分給每一個子控件 surplusChild = (int) (surplus / children.size()+0.5); } ------- child.measure(MeasureSpec.makeMeasureSpec(child.getMeasuredWidth()+surplusChild,MeasureSpec.EXACTLY) ,MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY));
源碼下載地址:https://github.com/gdutxiaoxu/CustomViewDemo.git
百度定位後在地圖上顯示並點擊彈出氣泡
要在 App 裡做「定位 → 在地圖上標記 → 點擊標記彈出資訊」這條流程,百度地圖 SDK 是最常見的選擇之一。本文整理從申請金鑰到跑通效果的完整步驟。 步驟一:申請金
利用 imeOptions 屬性把鍵盤回車鍵改成搜尋、下一步等功能鍵
在 Android 中,鍵盤輸入是使用者互動最常用、最直接的手段。關於鍵盤輸入,有幾點可以提升使用體驗。 第一:讓彈出的鍵盤整體頁面上移,避免遮擋控件。需在 Andro
Android Studio 常用設定整理:SDK 版本、配色、快捷鍵
換了 IDE 之後總要重新調一遍環境,把常用設定記錄下來省得每次翻找。 一、修改 SDK 版本 開啟 File → Project Structure...,接著選 M
Android PopupWindow 仿微信底部彈出效果
專案中 PopupWindow 的使用頻率很高,是相當實用的元件。本文示範一款仿微信風格的底部彈出視窗,可直接套用到專案。先看成果: 一、彈出視窗版面 版面相當簡單,以