Android 流式佈局

      雙十一到了,做爲一個程序員除了買(bai)買(jia)買(duo)買(shou)以外,也不要忘了學習,今天咱們來看Android的流式佈局。 所謂流式佈局指的是ViewGroup中同一行的寬度不足以容納下一個子view時,進行換行處理,而不須要考慮子view的大小,每一行的高度以其中最高者爲準。Talk is cheap, Show you the code。java

    自定義ViewGroup的三種方式:

  1. 經過繼承現有的ViewGroup(好比LinearLayout)重寫 onMeasure() 來修改已有的 ViewGroup的尺寸,好比你須要一個正方形的LinearLayout,你就能夠在onMeasure()中先調用super.onMeasure()測量出原始高度,而後經過getMesureHeight(),getMesuseWidth()得到原始寬高,將他們的寬高設爲同樣就行了,調用setMeasuredDimension()就能夠了,這麼樣是否是很簡(ma)單(fan);
  2. 重寫 onMeasure() 來全新定製自定義 View 的尺寸,一樣也是onMeasure()中,這時你就能夠根據本身須要是否調用super.onMeasure(),而後根據本身的算法,得出寬高,調用setMeasuredDimension()就能夠了;
  3. 重寫 onMeasure()onLayout() 來全新定製自定義 ViewGroup 的內部佈局,這種方式不僅僅須要測量自己本身的寬高,還要根據須要計算每一個子view的位置,稍微複雜一些,本次的流式佈局就是經過這種方式實現的。

實現過程:

下面這張圖是扔物線大神視頻截圖,這裏直接拿來用,別頂,要臉!!android

簡單講解一下整個過程:git

大致上分爲測量尺寸過程以及佈局過程程序員

測量尺寸過程:ViewGroup 的mesure()方法被父View調用,進而調用到 onMeasure() ,在onMeasuse()中會調用全部子 View 的 measure() 讓它們進行自我測量,並根據子 View 計算出的但願的尺寸來計算出它們的實際尺寸和位置(注意是但願的尺寸,不是最終尺寸,好比ViewGroup 的寬爲100dp,有一個子View的寬度爲200dp,顯然子View最多也只能是100dp的寬度)而後保存。同時,它也會根據子 View 的尺寸和位置來計算出本身的尺寸而後保存,到這裏咱們就肯定了ViewGroup自身的但願尺寸,以及它的子View的但願尺寸,那麼,具體字View怎麼擺放呢?這就到了下一個階段,佈局階段。github

佈局過程:VIewGrouplayout() 方法被父 View 調用,在 layout() 中它會取得父 View 傳進來的本身的位置和尺寸,而且調用 onLayout() 來進行實際的內部佈局ViewGroup 在 onLayout() 中會調用本身的全部子 View 的 layout() 方法,把它們的尺寸和位置傳給它們,讓子View完成佈局。算法

      光說不練假把式,Talk is cheap, Show you the code。

package com.example.administrator.xflowlayout;

/**
 * Created by SharksLee on 2016/07/19
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import java.util.HashMap;
import java.util.Map;

/**
 * @SharksLee lishaojie
 */
public class XFlowLayout extends ViewGroup {
    private int childHorizontalSpace;
    private int childVerticalSpace;
    private Map<Object, Location> mLocationMap;

    public XFlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray attrArray = context.obtainStyledAttributes(attrs, R.styleable.XLFlowLayout);
        mLocationMap = new HashMap<>();
        if (attrArray != null) {
            childHorizontalSpace = attrArray.getDimensionPixelSize(R.styleable.XLFlowLayout_childHorizontalSpace, 0);
            childVerticalSpace = attrArray.getDimensionPixelSize(R.styleable.XLFlowLayout_childVerticalSpace, 0);
            attrArray.recycle();
        }
    }

    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

    /**
     * 負責設置子控件的測量模式和大小 根據全部子控件設置本身的寬和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mLocationMap != null && !mLocationMap.isEmpty()) {
            mLocationMap.clear();
        }
        // 得到它的父容器爲它設置的測量模式和大小
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        // 若是是warp_content狀況下,記錄寬和高
        int width = 0;
        int height = 0;
        /**
         * 記錄每一行的寬度,width不斷取最大寬度
         */
        int lineWidth = 0;
        /**
         * 每一行的高度,累加至height
         */
        int lineHeight = 0;

        int count = getChildCount();
        int left = getPaddingLeft();
        int top = getPaddingTop();
        // 遍歷每一個子元素
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE)
                continue;
            // 測量每個child的寬和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 獲得child的lp
            LayoutParams lp = child.getLayoutParams();
            // 當前子空間實際佔據的寬度
            int childWidth = child.getMeasuredWidth() + childHorizontalSpace;
            // 當前子空間實際佔據的高度
            int childHeight = child.getMeasuredHeight() + childVerticalSpace;

            if (lp != null && lp instanceof MarginLayoutParams) {
                MarginLayoutParams params = (MarginLayoutParams) lp;
                childWidth += params.leftMargin + params.rightMargin;
                childHeight += params.topMargin + params.bottomMargin;
            }

            /**
             * 若是加入當前child的寬度,超出了最大寬度,則的到目前最大寬度給width,累加height 而後開啓新行
             */
            if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()) {
                width = Math.max(lineWidth, childWidth);// 取最大的
                lineWidth = childWidth; // 從新開啓新行,開始記錄
                // 疊加當前高度,
                height += lineHeight;
                // 開啓記錄下一行的高度
                lineHeight = childHeight;
                mLocationMap.put(child, new Location(left, top + height, childWidth + left - childHorizontalSpace, height + 

child.getMeasuredHeight() + top));
            } else {// 不然累加值lineWidth,lineHeight取最大高度
                mLocationMap.put(child, new Location(lineWidth + left, top + height, lineWidth + childWidth - 

childHorizontalSpace + left, height + child.getMeasuredHeight() + top));
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
        }
        width = Math.max(width, lineWidth) + getPaddingLeft() + getPaddingRight();
        height += lineHeight;
        sizeHeight += getPaddingTop() + getPaddingBottom();
        height += getPaddingTop() + getPaddingBottom();
        setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth : width, (modeHeight == MeasureSpec.EXACTLY) ? 

sizeHeight : height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE)
                continue;
            Location location = mLocationMap.get(child);
            child.layout(location.left, location.top, location.right, location.bottom);
        }
    }

    /**
     * 記錄子控件的座標
     */
    public static class Location {
        public int left;
        public int top;
        public int right;
        public int bottom;

        Location(int left, int top, int right, int bottom) {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }

    }
}

複製代碼

簡單講解一下思路:bash

在onMeasure()方法中,經過遍歷測量沒一個字View的寬高,若是加入當前child寬度,超出了最大寬度,測獲得目前最大寬度給width,width的做用是用來保存各行中最大寬度的,累加height 而後開啓新行。最後ide

setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth : width, (modeHeight == MeasureSpec.EXACTLY) ? 
複製代碼

注意一下modeWidth == MeasureSpec.EXACTLY表示寬度是在ViewGroup測量以前就已經肯定了的,好比佈局中的layout_width="100dp"或者layout_width="match_parent",這種狀況下直接 佈局

int sizeWidth = MeasureSpec.getSize(widthMeasureSpec)就能夠獲取到ViewGroup的寬度,不須要遍歷子View計算。注意這裏有個小技巧,我用mLocationMap在測量子View尺寸的時候就把它們位置信息保存起來,因此onLayout()方法很是簡單。學習

運行結果如圖:


今天雙十一,媳婦電商公司通宵纔有時間碼代碼,吹牛逼,有媳婦的人過了一個純粹的光棍節,/心塞!但至少我是有媳婦的人,/得意臉。

最後祝願你們節日快樂,碼農早日脫單,有錢也有機會清空敗家娘們的購物車/壞笑。

傳送門:github.com/SharksLee/F…

喜歡的給個星吧!
相關文章
相關標籤/搜索