編輯:關於 Android 程式設計
在度過 measure 階段、系統確定 View 的測量大小之後,流程便進入 layout 過程。此階段會決定視圖的顯示位置,也就是子 View 在其父控制項中的位置。
我們直接從 View 的 layout() 方法著手,拆解源碼。
// l, t, r, b 分別表示子 View 相對於父 View 的左、上、右、下座標
public void layout(int l, int t, int r, int b) {
if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
int oldL = mLeft;
int oldT = mTop;
int oldB = mBottom;
int oldR = mRight;
boolean changed = isLayoutModeOptical(mParent) ? setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
onLayout(changed, l, t, r, b);
mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnLayoutChangeListeners != null) {
ArrayList<OnLayoutChangeListener> listenersCopy =
(ArrayList<OnLayoutChangeListener>) li.mOnLayoutChangeListeners.clone();
int numListeners = listenersCopy.size();
for (int i = 0; i < numListeners; ++i) {
listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
}
}
}
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}
該方法主要完成兩件事:
1. 確定 View 在其父 View 中的位置(見第 13-14 行)。此處呼叫 setFrame(),將 l、t、r、b 分別與先前的 mLeft、mTop、mRight、mBottom 逐一比較,只要其中任一值發生變化,就判定該 View 的位置改變了。
2. 若位置發生變化,則呼叫 onLayout() 方法(見第 17 行)。
沿著這個思路,我們來看 onLayout() 的源碼:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) { }
咦,View 的 onLayout() 竟然是一個空方法!這是為什麼?先參考官方文檔的說明:
Called from layout when this view should assign a size and position to each of its children.
原來文檔說明了:在 layout 方法中呼叫的 onLayout() 用於指定每個子 View 的大小與位置。誰才有子 View 呢?当然是 ViewGroup!也就是說,ViewGroup 會透過 onLayout() 決定子 View 的顯示位置。
既然如此,我們就去看 ViewGroup 中的 onLayout() 如何實作:
protected abstract void onLayout(boolean changed, int l, int t, int r, int b);
咦,ViewGroup 的 onLayout() 竟然是一個抽象方法!這意味著 ViewGroup 的子類都必須重寫這個方法,實作各自的邏輯。像是 FrameLayout、LinearLayout、RelativeLayout 等布局都需重寫此方法,在其中依各自的布局規則確定子 View 的位置。
以下以 LinearLayout 為例,看看 ViewGroup 對 onLayout() 的實作。
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (mOrientation == VERTICAL) {
layoutVertical(l, t, r, b);
} else {
layoutHorizontal(l, t, r, b);
}
}
在 LinearLayout 的 onLayout() 中分別處理水平與垂直布局,此處選擇 layoutVertical() 繼續往下看。
void layoutVertical(int left, int top, int right, int bottom) {
final int paddingLeft = mPaddingLeft;
int childTop;
int childLeft;
final int width = right - left;
int childRight = width - mPaddingRight;
int childSpace = width - paddingLeft - mPaddingRight;
final int count = getVirtualChildCount();
final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
switch (majorGravity) {
case Gravity.BOTTOM:
childTop = mPaddingTop + bottom - top - mTotalLength;
break;
case Gravity.CENTER_VERTICAL:
childTop = mPaddingTop + (bottom - top - mTotalLength) / 2;
break;
case Gravity.TOP:
default:
childTop = mPaddingTop;
break;
}
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child == null) {
childTop += measureNullChild(i);
} else if (child.getVisibility() != GONE) {
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
int gravity = lp.gravity;
if (gravity < 0) {
gravity = minorGravity;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = paddingLeft + ((childSpace - childWidth) / 2) + lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = childRight - childWidth - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = paddingLeft + lp.leftMargin;
break;
}
if (hasDividerBeforeChildAt(i)) {
childTop += mDividerHeight;
}
childTop += lp.topMargin;
setChildFrame(child, childLeft, childTop + getLocationOffset(child), childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
這裡的邏輯並不簡單,我們看幾個關鍵步驟。
第一步:計算 child 可使用空間的大小(見第 8 行)。
第二步:取得子 View 的數量(見第 10 行)。
第三步:計算 childTop,藉此確定子 View 的起始布局位置(見第 12-28 行)。
第四步:確定每個子 View 的位置(見第 30-74 行),這是最關鍵的步驟:
1. 取得子 View 測量後的寬與高(見第 35-36 行),此處的 childWidth 與 childHeight 即為 measure 階段確立的值。
2. 取得子 View 的 LayoutParams(見第 38-39 行)。
3. 依子 View 的 LayoutParams 確定其位置(見第 41-69 行)。可以發現 setChildFrame() 中又呼叫了 View 的 layout() 來確定子 View 的位置。
至此我們就能理清整個思路:ViewGroup 先呼叫 layout() 確定自己在父 View 中的位置,接著呼叫 onLayout() 確定每個子 View 的位置,而每個子 View 又會呼叫 View 的 layout() 確定自己在 ViewGroup 中的位置。概括來說:View 的 layout() 用於確定自身在父 View 中的位置,ViewGroup 的 onLayout() 則用於確定子 View 的位置。
為了更直觀地理解,我們用一個簡單範例模擬 ViewGroup 的 onLayout() 過程。首先自訂一個 ViewGroup:
public class ViewGroupSubClass extends ViewGroup {
public ViewGroupSubClass(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
if (childCount > 0) {
View child = getChildAt(0);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
if (childCount > 0) {
View child = getChildAt(0);
int measuredWidth = child.getMeasuredWidth();
int measuredHeight = child.getMeasuredHeight();
child.layout(0, 0, measuredWidth, measuredHeight);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
主要步驟如下:
第一步:在 onMeasure() 中測量子 View。
第二步:在 onLayout() 中確定子 View 的位置。
定義好 ViewGroup 後,將其放入布局檔中:
<RelativeLayout android:background="#A5FD01" android:gravity="center"
android:layout_height="match_parent" android:layout_width="match_parent"
tools:context="com.cc.testlayout.MainActivity"
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools">
<com.cc.testlayout.ViewGroupSubClass
android:layout_height="wrap_content" android:layout_width="wrap_content">
<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content"
android:src="@drawable/j" />
</com.cc.testlayout.ViewGroupSubClass>
</RelativeLayout>
程式碼與布局都備齊後,運行看看效果。

如圖所示,我將一個 ImageView 放進自訂 ViewGroup 中展示了一張照片。
至此,我們已經看完 measure 與 layout 兩個過程,針對一些常見問題做個小結:
1. 取得 View 測量大小 measuredWidth 與 measuredHeight 的時機。在複雜或極端情況下,系統可能多次執行 measure,因此在 onMeasure() 中取值並不準確。為避免此問題,最好在下一階段即 onLayout() 中獲取。
2. getMeasuredWidth() 與 getWidth() 的差異。絕大多數情況兩者回傳值相同,但相同並不代表它們是同一個東西。首先,取得時機不同:measure() 結束後即可呼叫 getMeasuredWidth(),而 getWidth() 需在 layout() 結束後才能呼叫以取得實際大小。其次,計算方式不同:getMeasuredWidth() 的返回值透過 setMeasuredDimension() 得到,而 getWidth() 的返回值是「右座標減左座標(right-left)」計算而來。
3. 關於 View 座標:view.getLeft()、view.getRight()、view.getBottom()、view.getTop() 這四個方法用於取得子 View 相對於父 View 的位置。請注意:getLeft() 表示子 View 左邊距父 View 左邊的距離;getRight() 表示子 View 右邊距父 View 左邊的距離;getTop() 表示子 View 上邊距父 View 上邊的距離;getBottom() 表示子 View 下邊距父 View 上邊的距離。參考下圖:

4. 直接繼承 ViewGroup 可能帶來的複雜處理。剛才我們用簡單範例模擬了 ViewGroup 的 onLayout() 過程,看似簡單,實際專案中的情況可能遠比這複雜得多。例如 ViewGroup 中包含多個 View,每個 View 都設定了 padding 與 margin,還可能包含各種嵌套。此時在 onMeasure() 與 onLayout() 中都要耗費大量精力處理這些問題。因此一般情況下,我們可以選擇繼承 LinearLayout、RelativeLayout 等系統現成的布局,以簡化這兩部分的處理。
Android Studio 整合百度語音合成服務教學
語音合成又稱 TTS,顧名思義就是把文字轉換成語音,讓應用可以「說話」。在 Android 中,可以整合第三方語音服務來快速實現這個能力。本文以百度語音合成為例,說明在
Android 事件處理機制總結:基於回調的事件處理
一、Android 中的事件處理方法 事件處理的本質,是響應用戶的 UI 動作,從而提升應用程序的交互性。Android 中的事件處理主要分為三類: 1. 基於監聽的事件
Android Dialog 使用大全:五種常見對話框一次學會
對話框是與使用者確認、選擇、輸入資訊時最直接的互動元件。Android 的 AlertDialog.Builder 提供了足夠的彈性,從簡單提示到完全自訂版面都能勝任。
Android 實現在線音樂播放:MediaPlayer 與緩衝進度
在 Android 中播放網路音樂,通常會使用 MediaPlayer。若希望使用者看到緩衝情形,可搭配 SeekBar 的次要進度與 MediaPlayer 的緩衝更新