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

Android 自定義控件(二)——onLayout 詳解

編輯:關於 Android 程式設計

先講個笑話:一個乞丐看程序員寫程式,程序員遇到一個怎麼都解決不了的問題,乞丐說「你少打了個分號」,程序員照做,問題果然解決了,於是問:「你怎麼知道?」乞丐笑笑說:「我以前就是幹這個的。」玩笑歸玩笑,本篇我們要認真學習的內容如下:

本篇你將學到:

① 自定義控件中 onLayout 的源碼分析
② getLeft、getRight、getWidth、getHeight 的含義
③ 用一個例子理解自定義控件 onLayout 的過程
④ getMeasureWidth 和 getWidth 的區別

如有謬誤歡迎批評指正,如有疑問歡迎留言。

1. 簡單回顧

上一篇我們詳細講了 onMeasure 方法:在 onMeasure 中最終呼叫 setMeasuredDimension 確定控件大小。若自定義一個 View,測量自身大小即可;若是 ViewGroup,則需遍歷所有子 View 並逐一測量。測量子 View 時需要 measureWidth 與 measureHeight 兩個參數,它們由父布局傳入,也就是說子 View 的大小由父 View 與子 View 本身共同決定。

2. 源碼分析

今天我們探討自定義控件的第二步 onLayout,即確定控件的位置。上篇提到 performTraversals 會先呼叫 host.measure,之後呼叫 host.layout 對 View 定位。先看 layout 的源碼:

public final void layout(int l, int t, int r, int b) {
    boolean changed = setFrame(l, t, r, b);
    if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
        onLayout(changed, l, t, r, b);
        mPrivateFlags &= ~LAYOUT_REQUIRED;
    }
    mPrivateFlags &= ~FORCE_LAYOUT;
}

其中呼叫了 setFrame:

protected boolean setFrame(int left, int top, int right, int bottom) {
    boolean changed = false;
    if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
        changed = true;
        mLeft = left;
        mTop = top;
        mRight = right;
        mBottom = bottom;
    }
    return changed;
}

setFrame 把 left、top、right、bottom 四個值保存下來,也就是子 View 相對於父 View 的左上右下距離,這四個值決定了子 View 在父 View 中的位置。你會發現 layout 和 measure 一樣,內部呼叫了 onLayout。先看 View 的 onLayout:

protected void onLayout(boolean changed, int left, int top, int right, int bottom) { }

空的?其實想一想就明白:onLayout 的目的是確定子 View 在父 View 中的位置,這一步理應由父 View 決定,所以在 View 中它是空實作。那再看 ViewGroup 的 onLayout:

@Override protected abstract void onLayout(boolean changed, int l, int t, int r, int b);

它是抽象方法,這意味著自定義 ViewGroup 時必須實作 onLayout。它透過四個參數 l、t、r、b(代表距父 View 左、上、右、下的距離)來確定子 View 位置。

四個方法的含義如下:

mLeft——getLeft():子 View 左邊界到父 View 左邊界的距離

mTop——getTop():子 View 頂部到父 View 頂部的距離

mRight——getRight():子 View 右邊界到父 View 左邊界的距離

mBottom——getBottom():子 View 底部到父 View 頂部的距離

public final int getLeft() { return mLeft; }
public final int getTop() { return mTop; }
public final int getRight() { return mRight; }
public final int getBottom() { return mBottom; }
public final int getWidth() { return mRight - mLeft; }
public final int getHeight() { return mBottom - mTop; }
public final int getMeasuredWidth() { return mMeasuredWidth; }
public final int getMeasuredHeight() { return mMeasuredHeight; }

仔細看會發現還有成對的 getMeasuredWidth/getMeasuredHeight 與 getWidth/getHeight,它們有何區別?以 getMeasuredWidth 和 getWidth 為例:

① getMeasuredWidth() 在 measure() 結束後即可取得,返回值是 mMeasuredWidth,也就是上一篇透過 setMeasuredDimension() 設定出來的值;而 getWidth() 要在 layout() 結束後才能取得,返回值是 mRight − mLeft,這兩個值是在 layout() 的 setFrame 方法中才設定的。

② getMeasuredWidth() 的值透過 setMeasuredDimension() 設定,而 getWidth() 的值則是視圖右邊座標減去左邊座標算出來的。網上對這兩者有不少誤解,我會另寫一篇詳細說明。

3. 小例子

接下來用一個例子理解 layout 過程:自定義一個 ViewGroup,讓其子 View 在螢幕中間水平排列。思路是:①取得螢幕高度;②取得子 View 寬高,用螢幕高度與子 View 高度算出 layout 時子 View 到父 View 頂端的距離;③因為子 View 水平排列,需設一個變量記錄子 View 到父 View 左邊界的距離,每次循環加上子 View 寬度以設定下一個子 View 的左侧距離。

先看效果圖:

public class MyViewGroup extends ViewGroup {
    private Context mContext;
    private int sreenH;
    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        sreenH = getScreenSize(((Activity) mContext))[1];
    }
    @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
    }
    @Override protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int mLeft = 0;
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            int childViewHeight = childView.getMeasuredHeight();
            int childViewWidth = childView.getMeasuredWidth();
            int height = sreenH / 2 - childViewHeight / 2;
            childView.layout(mLeft, height, mLeft + childViewWidth, height + childViewHeight);
            mLeft += childViewWidth;
        }
    }
    public static int[] getScreenSize(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return new int[] { metrics.widthPixels, metrics.heightPixels };
    }
}

布局檔:

<com.example.customviewpractice.MyViewGroup xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測試一" />
    <Button android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測試二" />
    <Button android:id="@+id/btn3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測試三" />
    <Button android:id="@+id/btn4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測試四" />
</com.example.customviewpractice.MyViewGroup>

這個例子沒有做換行處理,重點是學習 layout 的用法。掌握自定義控件的流程後,你完全可以進一步自定義一個 FlowLayout。

4. 總結

至此,自定義控件的基礎知識 onMeasure 與 onLayout 就講完了。剛開始我也很畏懼這部分內容,覺得難,但沉下心來認真梳理思路後,會發現並不那麼難。有了這兩篇的基礎,我們就能動手實現一些小的自定義控件了。做自定義控件時思路很重要,只有把基礎打牢,才能按照設計實現預期效果。學習程式設計就是這樣,需要日積月累形成自己的思路。

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