在經(jīng)過measure階段以后,系統(tǒng)確定了View的測(cè)量大小,接下來就進(jìn)入到layout的過程。
在該過程中會(huì)確定視圖的顯示位置,即子View在其父控件中的位置。
嗯哼,我們直接扒開源碼從View的layout( )開始入手。
//l, t, r, b分別表示子View相對(duì)于父View的左、上、右、下的坐標(biāo)
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;
13 boolean changed = isLayoutModeOptical(mParent) ?
14 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15
16 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17 onLayout(changed, l, t, r, b);
18 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
19
20 ListenerInfo li = mListenerInfo;
21 if (li != null && li.mOnLayoutChangeListeners != null) {
22 ArrayList<OnLayoutChangeListener> listenersCopy =
23 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
24 int numListeners = listenersCopy.size();
25 for (int i = 0; i < numListeners; ++i) {
26 listenersCopy.get(i).onLayoutChange(this,l,t,r,b,oldL,oldT,oldR,oldB);
27 }
}
}
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}
在該方法中的主要實(shí)現(xiàn)
1 :確定該View在其父View中的位置,請(qǐng)參見代碼第13-14行。
在該處調(diào)用setFrame()方法,在該方法中把l,t, r, b分別與之前的mLeft,mTop,mRight,mBottom一一作比較,假若其中任意一個(gè)值發(fā)生了變化,那么就判定該View的位置發(fā)生了變化
2: 若View的位置發(fā)生了變化則調(diào)用onLayout()方法,請(qǐng)參見代碼第17行
嗯哼,我們就順著這個(gè)思路去看看onLayout()的源碼
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {}
額,View的onLayout()方法竟然是一個(gè)空方法!這是為啥呢?
先瞅瞅官方文檔對(duì)該方法的介紹:
Called from layout when this view should assign a size and position to each of its children.
噢,原來文檔中說了:在layout方法中調(diào)用該onLayout()用于指定子View的大小和位置。
誰才有子View呢?用你的小腦袋瓜想想。
哇哈,當(dāng)然是ViewGroup!
這也就是說:ViewGroup會(huì)調(diào)用onLayout()決定子View的顯示位置。
好吧,既然如此就去看ViewGroup中的onLayout()方法是怎么實(shí)現(xiàn)的;嗯哼,接著看源碼
protected abstract void onLayout(boolean changed,int l, int t, int r, int b);
額,ViewGroup的onLayout()竟然是一個(gè)抽象方法!這就意味著啥呢?
這就是說ViewGroup的子類都必須重寫這個(gè)方法,實(shí)現(xiàn)自己的邏輯。比如:FrameLayou,LinearLayout,RelativeLayout等等布局都需要重寫這個(gè)方法,在該方法內(nèi)依據(jù)各自的布局規(guī)則確定子View的位置。
在此以LinearLayout為例,看看ViewGroup對(duì)于onLayout()方法的實(shí)現(xiàn)。
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()繼續(xù)往下看。
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;
8 int childSpace = width - paddingLeft - mPaddingRight;
9
10 final int count = getVirtualChildCount();
11
12 final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
13 final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
14
15 switch (majorGravity) {
16 case Gravity.BOTTOM:
17 childTop = mPaddingTop + bottom - top - mTotalLength;
18 break;
19
20 case Gravity.CENTER_VERTICAL:
childTop =mPaddingTop+(bottom-top-mTotalLength) / 2;
break;
case Gravity.TOP:
default:
childTop = mPaddingTop;
27 break;
28 }
30 for (int i = 0; i < count; i++) {
31 final View child = getVirtualChildAt(i);
32 if (child == null) {
33 childTop += measureNullChild(i);
34 } else if (child.getVisibility() != GONE) {
35 final int childWidth = child.getMeasuredWidth();
36 final int childHeight = child.getMeasuredHeight();
37
38 final LinearLayout.LayoutParams lp =
39 (LinearLayout.LayoutParams) child.getLayoutParams();
40
41 int gravity = lp.gravity;
42 if (gravity < 0) {
43 gravity = minorGravity;
44 }
45 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;
}
66
67 childTop += lp.topMargin;
68 setChildFrame(child,childLeft,childTop+ getLocationOffset(child),
69 childWidth, childHeight);
70 childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
71
72 i += getChildrenSkipCount(child, i);
}
}
}
這里的邏輯不是特別簡(jiǎn)單,我們看幾個(gè)重要的步驟。
第一步:
計(jì)算child可使用空間的大小,請(qǐng)參見代碼第8行
第二步:
獲取子View的個(gè)數(shù),請(qǐng)參見代碼第10行
第三步:
計(jì)算childTop從而確定子View的開始布局位置,請(qǐng)參見代碼第12-28行
第四步:
確定每個(gè)子View的位置,請(qǐng)參見代碼第30-74行
這一步是最關(guān)鍵的步驟,我們瞅瞅它的主要操作
1、 得到子View測(cè)量后的寬和高,請(qǐng)參見代碼第35-36行. 這里獲取到的childWidth和childHeight就是在measure階段所確立的寬和高
2 、得到子View的LayoutParams,請(qǐng)參見代碼第38-39行.
3 、依據(jù)子View的LayoutParams確定子View的位置,請(qǐng)參見代碼第41-69行.
我們可以發(fā)現(xiàn)在setChildFrame()中又調(diào)用了View的layout()方法來確定子View的位置。
到這我們就可以理清楚思路了:
ViewGroup首先調(diào)用了layout()確定了自己本身在其父View中的位置,然后調(diào)用onLayout()確定每個(gè)子View的位置,每個(gè)子View又會(huì)調(diào)用View的layout()方法來確定自己在ViewGroup的位置。
概況地講:
View 的 layout() 方法用于 View 確定自己本身在其父View的位置
ViewGroup 的 onLayout() 方法用于確定子View的位置
為了更好的理解,在此用一個(gè)簡(jiǎn)單的示例模擬ViewGroup的onLayout()過程
首先我們自定義一個(gè)ViewGroup
package com.cc.testlayout;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.view.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()中測(cè)量子View
第二步:
在onLayout()中確定子View的位置
定義好ViewGroup之后,將其放入布局文件中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#A5FD01"
tools:context="com.cc.testlayout.MainActivity">
<com.cc.testlayout.ViewGroupSubClass
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/j" />
</com.cc.testlayout.ViewGroupSubClass>
</RelativeLayout>
代碼有了,布局文件也寫了,運(yùn)行一下瞅瞅效果。 嗯哼,看到了吧,我把一個(gè)ImageView放入自定義ViewGroup中展示了我女朋友的照片。
至此,我們已經(jīng)看完了measure和layout這兩個(gè)過程,對(duì)于一些問題我們做一個(gè)小的總結(jié)
- 獲取View的測(cè)量大小measuredWidth和measuredHeight的時(shí)機(jī)。
在某些復(fù)雜或者極端的情況下系統(tǒng)會(huì)多次執(zhí)行measure過程,所以在onMeasure()中去獲取View的測(cè)量大小得到的是一個(gè)不準(zhǔn)確的值。為了避免該情況,最好在onMeasure()的下一階段即onLayout()中去獲取。 - getMeasuredWidth()和getWidth()的區(qū)別
在絕大多數(shù)情況下這兩者返回的值都是相同的,但是結(jié)果相同并不說明它們是同一個(gè)東西。
- 首先,它們的獲取時(shí)機(jī)是不同的。
在measure()過程結(jié)束后就可以調(diào)用getMeasuredWidth()方法獲取到View的測(cè)量大小,而getWidth()方法要在layout()過程結(jié)束后才能被調(diào)用從而獲取View的實(shí)際大小。 - 其次,它們返回值的計(jì)算方式不同。
getMeasuredWidth()方法中的返回值是通過setMeasuredDimension()方法得到的,這點(diǎn)我們之前已經(jīng)分析過,在此不再贅述;而getWidth()方法中的返回值是通過View的右坐標(biāo)減去其左坐標(biāo)(right-left)計(jì)算出來的。
-
剛才說到了關(guān)于View的坐標(biāo),在這就不得不提一下:
view.getLeft(),view.getRight(),view.getBottom(),view.getTop();
這四個(gè)方法用于獲取子View相對(duì)于父View的位置。
但是請(qǐng)注意:
getLeft( )表示子View的左邊距離父View的左邊的距離
getRight( )表示子View的右邊距離父View的左邊的距離
getTop( )表示子View的上邊距離父View的上邊的距離
getBottom( )表示子View的下邊距離父View的上邊的距離
在此,畫一個(gè)示例圖作為參考
坐標(biāo)示例圖 - 直接繼承自ViewGroup可能帶來的復(fù)雜處理。 剛通過一個(gè)例子簡(jiǎn)單模擬了ViewGroup的onLayout()過程;其實(shí),說簡(jiǎn)單已經(jīng)算是含蓄的了;如果要粗暴地說那就是簡(jiǎn)單得令人發(fā)指。因?yàn)轫?xiàng)目開發(fā)中實(shí)際的情況可能遠(yuǎn)比這個(gè)復(fù)雜;比如,在ViewGroup中包含了多個(gè)View,每個(gè)View都設(shè)置了padding和margin,除此之外還可能包含各種嵌套。在這種情況下,我們?cè)趏nMeasure()和onLayout()中都要花費(fèi)大量的精力來處理這些問題。所以在一般情況下,我們可以選擇繼承自LinearLayout,RelativeLayout等系統(tǒng)已有的布局從而簡(jiǎn)化這兩部分的處理。
who is the next one? ——> draw
自定義View系列教程01--常用工具介紹
自定義View系列教程02--onMeasure源碼詳盡分析
自定義View系列教程03--onLayout源碼詳盡分析
自定義View系列教程04--Draw源碼分析及其實(shí)踐
自定義View系列教程05–示例分析
自定義View系列教程06–詳解View的Touch事件處理
自定義View系列教程07–詳解ViewGroup分發(fā)Touch事件
自定義View系列教程08–滑動(dòng)沖突的產(chǎn)生及其處理
參考文章
Android LayoutInflater原理分析,帶你一步步深入了解View(一)
Android視圖繪制流程完全解析,帶你一步步深入了解View(二)
Android視圖狀態(tài)及重繪流程分析,帶你一步步深入了解View(三)
Android自定義View的實(shí)現(xiàn)方法,帶你一步步深入了解View(四)