Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自訂 View 知識儲備:LayoutParams 到底是什麼?

編輯:關於 Android 程式設計

上一篇《自訂 View 知識儲備 — View 的繪製流程》裡,我整理過動手寫控制項之前必須先弄懂的基礎。其中提到一個關鍵環節:View 最終量到的尺寸,是由父容器的 MeasureSpec 與 View 自身的 LayoutParams 共同決定的。MeasureSpec 已經在上一篇講透,剩下的 LayoutParams,就在這裡一次說清楚。

LayoutParams 是什麼?

顧名思義,Layout Parameters,也就是「版面參數」。我很早就跟它天天打照面了 —— 寫 XML 版面時最常敲的就是 android:layout_width="match_parent" 這類寫法。例如:

<TextView
    android:background="@color/colorAccent"
    android:gravity="center"
    android:layout_gravity="center"
    android:layout_height="100dp"
    android:layout_marginLeft="10dp"
    android:layout_width="match_parent"
    android:text="英明神武蘑菇君"
    android:textColor="@color/white" />

那時候我心裡一直有個疑問:textColor、background 這些描述屬性都很正常,為什麼寬高非得加上「layout_」前綴?講道理,直接寫 width、height 不就完了?

後來 LayoutParams 給了我答案:layout_width 並不是 View 自己的屬性,而是 LayoutParams 的;而且不只這一個,所有以「layout_」開頭的屬性都歸它管,所以要打上自己的標記。(囂張什麼,到頭來你自己不也是 View 的一部分。)

於是問題變成:既然這些屬性是 LayoutParams 定義的,為什麼會出現在描述 View 的 XML 裡?兩者之間到底什麼關係?

官方文件怎麼說

LayoutParams are used by views to tell their parents how they want to be laid out.(LayoutParams 是 View 用來告訴父容器「我希望被怎麼擺放」的溝通管道。)

The base LayoutParams class just describes how big the view wants to be for both width and height.(基類 ViewGroup.LayoutParams 只描述 View 期望的寬與高。)

There are subclasses of LayoutParams for different subclasses of ViewGroup.(不同 ViewGroup 各自對應不同的 LayoutParams 子類。)

翻譯可以再直白一點:textColor、background 這類屬性只跟 View 本身有關,無論它被放進哪個容器都不會改變;但 layout_width、layout_marginLeft 這種屬性,是跟父容器綁在一起的。是父容器透過 LayoutParams 把這些「layout_」屬性提供給孩子,也是父容器依照孩子的 LayoutParams 來決定怎麼量測、怎麼安放。

換句話說,View 的 LayoutParams 一旦離開父容器,就失去意義了。

基類 ViewGroup.LayoutParams 是 ViewGroup 裡的一個靜態內部類(這本身就說明了它與父容器關係匪淺),功能非常樸素,只提供 width 與 height,對應 XML 裡的 layout_width 和 layout_height。所以任何系統容器或自訂 ViewGroup,它的子 View 一定都能寫這兩個屬性。

有了這個基類之後,自訂 ViewGroup 時就可以實作自己的 LayoutParams,為孩子們提供更多專屬的版面屬性。系統內建的容器很多,LayoutParams 子類自然也少不了。

ViewGroup.MarginLayoutParams

先看最常用的一個:ViewGroup.MarginLayoutParams,顧名思義就是提供 margin 屬性的那一支。

public static class MarginLayoutParams extends ViewGroup.LayoutParams {
    public int leftMargin;
    public int topMargin;
    public int rightMargin;
    public int bottomMargin;
    private int startMargin = DEFAULT_MARGIN_RELATIVE;
    private int endMargin = DEFAULT_MARGIN_RELATIVE;
    ...
}

前四個是我們在版面檔裡最熟悉的;後面的 startMargin 與 endMargin 則是為了支援 RTL(由右至左)版面而生的替代品。

一般情況下 View 的起始端就是左邊,但有些語言(例如阿拉伯語)是由右往左書寫。Android 4.2 之後 Google 引入了 RTL 版面支援,並建議改用 MarginStart / MarginEnd 取代 MarginLeft / MarginRight,讓 App 在兩種文字方向的螢幕上都能有一致的呈現。

除了單方向間距,我們也會用 layout_margin 一次設定四邊。來看源碼裡這段處理:

public MarginLayoutParams(Context c, AttributeSet attrs) {
    super();
    TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout);
    setBaseAttributes(a,
        R.styleable.ViewGroup_MarginLayout_layout_width,
        R.styleable.ViewGroup_MarginLayout_layout_height);

    int margin = a.getDimensionPixelSize(
        com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1);
    if (margin >= 0) {
        leftMargin = margin;
        topMargin = margin;
        rightMargin = margin;
        bottomMargin = margin;
    } else {
        leftMargin = a.getDimensionPixelSize(
            R.styleable.ViewGroup_MarginLayout_layout_marginLeft, UNDEFINED_MARGIN);
        if (leftMargin == UNDEFINED_MARGIN) {
            mMarginFlags |= LEFT_MARGIN_UNDEFINED_MASK;
            leftMargin = DEFAULT_MARGIN_RESOLVED;
        }
        ...
    }
    ...
}

邏輯很清楚:先讀 layout_margin,有值就四邊一起套;沒設定才回頭去讀 layout_marginLeft、layout_marginRight 等單邊屬性。因此可以得出一個常被忽略的小結論:

在 XML 版面中,layout_margin 的值會覆蓋 layout_marginLeft、layout_marginRight 等單邊屬性。

以前我還天真的以為「屬性寫在後面就會蓋掉前面」。後來讀懂源碼,才發現真正的原因不在撰寫順序,而在解析邏輯本身。

揭開隱藏的 LayoutParams

初學 Android 時,我們其實一直在「偷偷摸摸」地用 LayoutParams —— 在 XML 裡借用容器的版面屬性替孩子排版,方便又能即時預覽,但缺點是版面被寫死,無法動態調整。想讓它動起來,还是得回到程式碼(畢竟 XML 最後也是被解析成程式碼邏輯的)。

那要從哪裡開始讀源碼?我認為有句話說得很對:

脫離場景談源碼,都是耍流氓。

既然 LayoutParams 是父容器提供給子 View 的,那麼在子 View 被加入父容器的那一刻,它就該有 LayoutParams 了。先看幾種常見的動態添加寫法:

LinearLayout parent = (LinearLayout) findViewById(R.id.parent);

// 1. 直接加一個「裸」的 TextView,不主動指定 LayoutParams
TextView textView = new TextView(this);
textView.setText("紅色蘑菇君");
textView.setTextColor(Color.RED);
parent.addView(textView);

// 2. 先手動設定好 LayoutParams,再加入
textView = new TextView(this);
textView.setText("綠色蘑菇君");
textView.setTextColor(Color.GREEN);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(300, 300);
textView.setLayoutParams(lp);
parent.addView(textView);

// 3. 加入的同時傳入建立好的 LayoutParams
textView = new TextView(this);
textView.setText("藍色蘑菇君");
textView.setTextColor(Color.BLUE);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT, 300);
parent.addView(textView, lp2);

三種寫法都繞不開 addView,來看它的幾個重載版本:

// 以下三個方法皆來自基類 ViewGroup
public void addView(View child) {
    addView(child, -1);
}

public void addView(View child, int index) {
    if (child == null) {
        throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
    }
    LayoutParams params = child.getLayoutParams();
    if (params == null) {
        params = generateDefaultLayoutParams();
        if (params == null) {
            throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
        }
    }
    addView(child, index, params);
}

public void addView(View child, LayoutParams params) {
    addView(child, -1, params);
}

addView(View child) 會轉呼叫帶 index 的版本,其中檢查了 child 的 LayoutParams,若為 null 就呼叫 generateDefaultLayoutParams() 補一個預設值。這很合理 —— 這世界上像我這麼懶的人太多,不給個預設選項,別說友誼的小船,就算泰坦尼克也說翻就翻。

那麼 LinearLayout 替我們 these 懶人準備了什麼預設值?

@Override
protected LayoutParams generateDefaultLayoutParams() {
    if (mOrientation == HORIZONTAL) {
        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    } else if (mOrientation == VERTICAL) {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }
    return null;
}

顯然 LinearLayout 覆寫了基類的實作:水平方向時,孩子的寬高都是 WRAP_CONTENT;垂直方向時,高度仍是 WRAP_CONTENT,寬度卻變成 MATCH_PARENT。這一點值得留意 —— 很可能就是因為偷懶,導致實際版面跟預期不一樣。所以上面第 1 種寫法並不推薦,第 2、3 種明確指定 LayoutParams 的方式更清楚、也更好改。

三個重載版本最終都會走到參數最完整的 addView(View child, int index, LayoutParams params):

public void addView(View child, int index, LayoutParams params) {
    ...
    requestLayout();
    invalidate(true);
    addViewInner(child, index, params, false);
}

private void addViewInner(View child, int index, LayoutParams params,
        boolean preventRequestLayout) {
    ...
    if (!checkLayoutParams(params)) {
        params = generateLayoutParams(params);
    }
    if (preventRequestLayout) {
        child.mLayoutParams = params;
    } else {
        child.setLayoutParams(params);
    }
    ...
}

接著它把髒活交給 addViewInner。而 LinearLayout 對應的兩個方法長這樣:

// 覆寫以進行 LayoutParams 的型別檢查
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
    return p instanceof LinearLayout.LayoutParams;
}

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

checkLayoutParams 檢查傳進來的 LayoutParams 是不是 LinearLayout 自己的型別;若不是,就由 generateLayoutParams 依既有屬性重新包一個正確的對象。父容器連我們偷懶、甚至寫錯型別都在背後默默收拾,只為了給孩子一個舒適的環境。

不過,父容器只能在 addView 的那一刻幫忙糾正;如果你事後自己去改 LayoutParams,它可就愛莫能助了。例如:

LinearLayout parent = (LinearLayout) findViewById(R.id.parent);
textView = new TextView(this);
textView.setText("此處有 BUG");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200, 200);
parent.addView(textView, lp);
textView.setLayoutParams(new ViewGroup.LayoutParams(100, 100)); // 型別不對

這會直接拋出 ClassCastException:

java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to
android.widget.LinearLayout$LayoutParams

這個錯誤想必大家都不陌生。原因是 textView 的父容器是 LinearLayout,我們卻硬塞了一個 ViewGroup 的 LayoutParams 進去;等到 LinearLayout 重新走繪製流程時,onMeasure 裡會做強制轉型:

LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();

於是 App 就斯巴達了。你可能會說:我知道父容器是誰,當然會給對的型別。話是沒錯,但實務上有很多時候,你沒辦法一眼看出某個 View 的 LayoutParams 究竟是哪一種 —— 這時候就得靠分析,而希望這篇能幫上忙。

自訂 LayoutParams

前面提過,幾乎每個容器都有自己的 LayoutParams 實作:LinearLayout、FrameLayout、RelativeLayout……所以自訂 ViewGroup 時,通常也要一起自訂 LayoutParams。

這裡用一個簡單的流式版面 FlowLayout 當例子:

FlowLayout:加入容器的子 View 由左至右依序排列,若目前這一行放不下下一個 View,就換到下一行。

假設我們希望 FlowLayout 提供一個 gravity 屬性,讓孩子能在同一列的垂直方向上選擇 top、center 或 bottom —— 這效果是不是很眼熟?跟 LinearLayout 給孩子的 layout_gravity 幾乎一樣。那就參考它的源碼:

public static class LayoutParams extends ViewGroup.MarginLayoutParams {
    public float weight;
    public int gravity = -1;

    public LayoutParams(Context c, AttributeSet attrs) {
        super(c, attrs);
        TypedArray a = c.obtainStyledAttributes(attrs,
                com.android.internal.R.styleable.LinearLayout_Layout);
        weight = a.getFloat(com.android.internal.R.styleable.LinearLayout_Layout_layout_weight, 0);
        gravity = a.getInt(com.android.internal.R.styleable.LinearLayout_Layout_layout_gravity, -1);
        a.recycle();
    }

    public LayoutParams(ViewGroup.LayoutParams p) { super(p); }
    public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); }

    public LayoutParams(LayoutParams source) {
        super(source);
        this.weight = source.weight;
        this.gravity = source.gravity;
    }
}

有幾個重點值得抄下來:

第一,LinearLayout 的 LayoutParams 繼承的是 ViewGroup.MarginLayoutParams,所以孩子天生就能用 margin。實務上絕大多數容器都直接繼承 MarginLayoutParams 而非 LayoutParams,我們的 FlowLayout 也照辦。

第二,com.android.internal.R.styleable.LinearLayout_Layout 其實就是系統在 attrs 裡配置的 declare-styleable,用來宣告這個容器能為孩子提供哪些屬性,IDE 的快捷提示也是靠它。自訂 FlowLayout 時,我們在 attrs.xml 裡寫成:

<declare-styleable name="FlowLayout_Layout">
</declare-styleable>

剩下的建構子,作用就是從傳入的 LayoutParams 把屬性複製過來。依葫蘆畫瓢,FlowLayout 的 LayoutParams 大致如下:

public static class LayoutParams extends ViewGroup.MarginLayoutParams {
    public int gravity = -1;

    public LayoutParams(Context c, AttributeSet attrs) {
        super(c, attrs);
        TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.FlowLayout_Layout);
        gravity = a.getInt(R.styleable.FlowLayout_Layout_android_layout_gravity, -1);
        a.recycle();
    }

    public LayoutParams(ViewGroup.LayoutParams p) { super(p); }
    public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); }

    public LayoutParams(LayoutParams source) {
        super(source);
        this.gravity = source.gravity;
    }
}

看起來挺簡單吧?那這篇就這樣結束……等等,好像漏了什麼。

回想前面分析 addView 的流程,ViewGroup 裡還這麼幾個方法:

public LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new LayoutParams(getContext(), attrs);
}
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return p; }
protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p != null; }

為了讓子 View 加入時能拿到正確的 LayoutParams,這幾個方法都必須一起覆寫(原因請回看上節)。LinearLayout 的作法是:

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

@Override
protected LayoutParams generateDefaultLayoutParams() {
    if (mOrientation == HORIZONTAL) {
        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    } else if (mOrientation == VERTICAL) {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }
    return null;
}

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

@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
    return p instanceof LinearLayout.LayoutParams;
}

至於 FlowLayout 該怎麼改寫這四個方法,聰明的你應該已經有答案了。

總結

這篇從自訂 View 的角度出發,結合源碼把 LayoutParams 梳理了一遍。不得不說,讀源碼來學一個知識點,效果遠勝死記結論 —— 至少下次遇到 ClassCastException 時,你會知道該去哪裡找答案。

寫作初期難免有疏漏,若有錯誤歡迎指正補充。

下一篇預告

接下來會記錄一個簡單自訂 ViewGroup —— 流式版面 FlowLayout 的完整實作,把《View 的繪製流程》裡的知識點和本篇的 LayoutParams 串起來。

另外,寫部落格的初期確實有點辛苦:腦中想寫的很多,真要落成文字時卻常有「愛你在心口難開」的尷尬。不過感覺到困難,通常意味著自己正在走上坡路。繼續撐下去,希望對自己與大家都有幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved