首先來介紹一下這個自定義View:
- (1)這個自定義View的名稱叫做 FlowLayout ,繼承自ViewGroup類;
- (2)在這個自定義View中,用戶可以放入所有繼承自View類的視圖,這個布局會自動獲取其寬高並排列在布局中,保證每一個視圖都完整的顯示在界面上;
- (3)如果用戶放入布局的視圖的總高度大於設置給這個視圖的高度,那么視圖就可以支持上下滾動;
- (4)可以在XML布局文件或JAVA文件中設置布局的padding屬性和子元素的margin屬性。
接下來簡單介紹一下在這個自定義View中用到的技術點:
- (1)用到了自定義View三大流程中的測量和布局流程,分別體現在 onMeasure() 和 onLayout() 兩個方法中;
- (2)在onMeasure()方法中,測量所有子元素的寬高,最后通過累加判斷得到自身要顯示的寬高;
- (3)在onMeasure()方法中還為所有子元素進行了分行,保證每個子元素都能完整的顯示在布局中,達到“流式布局”的功能需求;
- (4)在onLayout()方法中,一次取出所有子元素,獲取onMeasure()方法中測量的寬高,開始布局;
- (5)在上面的測量和布局過程中,都有將布局的 padding 屬性和元素的 margin 屬性考慮在內;
- (6)設置了這個布局中的子元素具有的LayoutParams:通過 generateLayoutParams() 方法設置;
- (7)在 onInterceptTouchEvent() 方法中對事件進行攔截,保證布局滾動和元素點擊不會產生沖突;
- (8)在 onTouchEvent() 方法中處理了觸摸事件,實現布局的滾動功能。
下面是這個自定義View—— FlowLayout 的實現代碼:
自定義View類 FlowLayout.java 中的代碼:
import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; /** * 自定義流式布局 */ public class FlowLayout extends ViewGroup { private List<List<View>> views; // 存放所有子元素(一行一行存儲) private List<View> lineViews; // 存儲每一行中的子元素 private List<Integer> heights; // 存儲每一行的高度 private boolean scrollable; // 是否可以滾動 private int measuredHeight; // 測量得到的高度 private int realHeight; // 整個流式布局控件的實際高度 private int scrolledHeight = 0; // 已經滾動過的高度 private int startY; // 本次滑動開始的Y坐標位置 private int offsetY; // 本次滑動的偏移量 private boolean pointerDown; // 在ACTION_MOVE中,視第一次觸發為手指按下,從第二次觸發開始計入正式滑動 public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * 初始化 */ private void init() { views = new ArrayList<>(); lineViews = new ArrayList<>(); heights = new ArrayList<>(); } /** * 計算布局中所有子元素的寬度和高度,累加得到整個布局最終顯示的寬度和高度 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); measuredHeight = MeasureSpec.getSize(heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); // 當前行的寬度和高度(寬度是子元素寬度的和,高度是子元素高度的最大值) int lineWidth = 0; int lineHeight = 0; // 整個流式布局最終顯示的寬度和高度 int flowLayoutWidth = 0; int flowLayoutHeight = 0; // 初始化各種參數(列表) init(); // 遍歷所有子元素,對子元素進行排列 int childCount = this.getChildCount(); for (int i = 0; i < childCount; i++) { View child = this.getChildAt(i); // 獲取到子元素的寬度和高度 measureChild(child, widthMeasureSpec, heightMeasureSpec); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); // 如果當前行中剩余的空間不足以容納下一個子元素,則換行 // 換行的同時,保存當前行中的所有元素,疊加行高,然后將行寬和行高重置為0 if (lineWidth + childWidth + lp.leftMargin + lp.rightMargin > widthSize - getPaddingLeft() - getPaddingRight()) { views.add(lineViews); lineViews = new ArrayList<>(); flowLayoutWidth = Math.max(flowLayoutWidth, lineWidth); // 以最寬的行的寬度作為最終布局的寬度 flowLayoutHeight += lineHeight; heights.add(lineHeight); lineWidth = 0; lineHeight = 0; } // 無論換不換行,都需要將元素添加到列表中、處理寬度和高度的值 lineViews.add(child); lineWidth += childWidth + lp.leftMargin + lp.rightMargin; lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin); // 處理最后一行,否則最后一行不能顯示 if (i == childCount - 1) { flowLayoutHeight += lineHeight; flowLayoutWidth = Math.max(flowLayoutWidth, lineWidth); heights.add(lineHeight); views.add(lineViews); } } // 得到最終的寬高 // 寬度:如果是EXACTLY模式,則遵循測量值,否則使用我們計算得到的寬度值 // 高度:只要布局中內容的高度大於測量高度,就使用內容高度(無視測量模式);否則才使用測量高度 int width = widthMode == MeasureSpec.EXACTLY ? widthSize : flowLayoutWidth + getPaddingLeft() + getPaddingRight(); realHeight = flowLayoutHeight + getPaddingTop() + getPaddingBottom(); if (heightMode == MeasureSpec.EXACTLY) { realHeight = Math.max(measuredHeight, realHeight); } scrollable = realHeight > measuredHeight; // 設置最終的寬高 setMeasuredDimension(width, realHeight); } /** * 對所有子元素進行布局 */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // 當前子元素應該布局到的X、Y坐標 int currentX = getPaddingLeft(); int currentY = getPaddingTop(); // 遍歷所有子元素,對每個子元素進行布局 // 遍歷每一行 for (int i = 0; i < views.size(); i++) { int lineHeight = heights.get(i); List<View> lineViews = views.get(i); // 遍歷當前行中的每一個子元素 for (int j = 0; j < lineViews.size(); j++) { View child = lineViews.get(j); // 獲取到當前子元素的上、下、左、右的margin值 MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int childL = currentX + lp.leftMargin; int childT = currentY + lp.topMargin; int childR = childL + child.getMeasuredWidth(); int childB = childT + child.getMeasuredHeight(); // 對當前子元素進行布局 child.layout(childL, childT, childR, childB); // 更新下一個元素要布局的X、Y坐標 currentX += lp.leftMargin + child.getMeasuredWidth() + lp.rightMargin; } currentY += lineHeight; currentX = getPaddingLeft(); } } /** * 滾動事件的處理,當布局可以滾動(內容高度大於測量高度)時,對手勢操作進行處理 */ @Override public boolean onTouchEvent(MotionEvent event) { // 只有當布局可以滾動的時候(內容高度大於測量高度的時候),才會對手勢操作進行處理 if (scrollable) { int currY = (int) event.getY(); switch (event.getAction()) { // 因為ACTION_DOWN手勢可能是為了點擊布局中的某個子元素,因此在onInterceptTouchEvent()方法中沒有攔截這個手勢 // 因此,在這個事件中不能獲取到startY,也因此才將startY的獲取移動到第一次滾動的時候進行 case MotionEvent.ACTION_DOWN: break; // 當第一次觸發ACTION_MOVE事件時,視為手指按下;以后的ACTION_MOVE事件才視為滾動事件 case MotionEvent.ACTION_MOVE: // 用pointerDown標志位只是手指是否已經按下 if (!pointerDown) { startY = currY; pointerDown = true; } else { offsetY = startY - currY; // 下滑大於0 // 布局中的內容跟隨手指的滾動而滾動 // 用scrolledHeight記錄以前的滾動事件中滾動過的高度(因為不一定每一次滾動都是從布局的最頂端開始的) this.scrollTo(0, scrolledHeight + offsetY); } break; // 手指抬起時,更新scrolledHeight的值; // 如果滾動過界(滾動到高於布局最頂端或低於布局最低端的時候),設置滾動回到布局的邊界處 case MotionEvent.ACTION_UP: scrolledHeight += offsetY; if (scrolledHeight + offsetY < 0) { this.scrollTo(0, 0); scrolledHeight = 0; } else if (scrolledHeight + offsetY + measuredHeight > realHeight) { this.scrollTo(0, realHeight - measuredHeight); scrolledHeight = realHeight - measuredHeight; } // 手指抬起后別忘了重置這個標志位 pointerDown = false; break; } } return super.onTouchEvent(event); } /** * 調用在這個布局中的子元素對象的getLayoutParams()方法,會得到一個MarginLayoutParams對象 */ @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } /** * 事件攔截,當手指按下或抬起的時候不進行攔截(因為可能這個操作只是點擊了布局中的某個子元素); * 當手指移動的時候,才將事件攔截; * 因此,我們在onTouchEvent()方法中,只能將ACTION_MOVE的第一次觸發作為手指按下 */ @Override public boolean onInterceptTouchEvent(MotionEvent ev) { boolean intercepted = false; switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: intercepted = false; break; case MotionEvent.ACTION_MOVE: intercepted = true; break; case MotionEvent.ACTION_UP: intercepted = false; break; } return intercepted; } }
布局文件 activity_main.xml 中的代碼如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <my.itgungnir.flowlayout.FlowLayout android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20.0dip"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="My name is ITGungnir" /> ......(省略N個Button) <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="20.0dip" android:text="Hello" /> ......(省略N個Button) <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="搜嘎" /> </my.itgungnir.flowlayout.FlowLayout> </LinearLayout>
這里注意:我給FlowLayout布局設置了padding為20.0dip;Hello那個按鈕的margin屬性也設置成了20.0dip,具體的效果見最后的運行效果圖。
主界面JAVA代碼中不需要書寫任何代碼。當然,我們也可以在Activity中通過JAVA代碼,動態生成View后添加到這個布局中。這里就不演示了。
項目的運行效果圖如下圖所示:

