自定義View從原始碼到應用
Android進階的書看了一遍又一遍,奈何總是看了又忘,忘了又看,于是打算將自己學的總結一下,也希望我總結的內容能對它人有所幫助!
在原始碼中有很多英文注釋,如果看不懂的可以用工具翻譯一下,我就不翻譯了
轉載請注明原作者,謝謝!
文章目錄
- 自定義View從原始碼到應用
- Scroller決議
- 事件分發機制
- 滑動沖突處理
- 外部攔截法
- 內部攔截法
- 解決ViewPager2的滑動沖突問題
- View的繪制
- 理解MeasureSpec
- View的MeasureSpec是怎么產生的
- ViewGroup的measure程序
- ViewGroup的layout程序
Scroller決議
關于View的滑動有很多種實作方式,使用Scroller可以實作View的彈性滑動
關于Scroller的基本使用不再贅述
首先看看Scroller的構造方法
/**
* Create a Scroller with the default duration and interpolator.
*/
public Scroller(Context context) {
this(context, null);
}
/**
* Create a Scroller with the specified interpolator. If the interpolator is
* null, the default (viscous) interpolator will be used. "Flywheel" behavior will
* be in effect for apps targeting Honeycomb or newer.
*/
public Scroller(Context context, Interpolator interpolator) {
this(context, interpolator,
context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB);
}
/**
* Create a Scroller with the specified interpolator. If the interpolator is
* null, the default (viscous) interpolator will be used. Specify whether or
* not to support progressive "flywheel" behavior in flinging.
*/
public Scroller(Context context, Interpolator interpolator, boolean flywheel) {
mFinished = true;
if (interpolator == null) {
mInterpolator = new ViscousFluidInterpolator();
} else {
mInterpolator = interpolator;
}
mPpi = context.getResources().getDisplayMetrics().density * 160.0f;
mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction());
mFlywheel = flywheel;
mPhysicalCoeff = computeDeceleration(0.84f); // look and feel tuning
}
通常我們都是使用第一個構造方法,那Scroller就會采用默認的插值器
一般我們在使用Scroller時,會重寫computeScroll()方法,并如此實作
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
postInvalidate();
}
}
這是為什么呢?
帶著這個疑問我們來看看 Scroller的startScroll方法
public void startScroll(int startX, int startY, int dx, int dy) {
startScroll(startX, startY, dx, dy, DEFAULT_DURATION);
}
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
mMode = SCROLL_MODE;
mFinished = false;
mDuration = duration;
mStartTime = AnimationUtils.currentAnimationTimeMillis();
mStartX = startX;
mStartY = startY;
mFinalX = startX + dx;
mFinalY = startY + dy;
mDeltaX = dx;
mDeltaY = dy;
mDurationReciprocal = 1.0f / (float) mDuration;
}
可以發現我們使用startScroll時并沒有導致View的滑動,在這個方法中只是記錄了滑動相關的值
那view是怎么滑動的呢?
我們在呼叫startScroll后會呼叫invalidate()方法(或者postInvalidate()方法,倆者的區別是invalidate要在UI執行緒中使用,而postInvalidate()可以不在UI執行緒中使用,這是因為postInvalidate底層使用了Handler)
這個方法會導致View的重繪,而View的重繪會導致View的draw方法被呼叫,View的draw方法被呼叫會導致
computeScroll被呼叫,而在我們重寫的computeScroll方法中,只要滿足mScroller.computeScrollOffset()就又會呼叫postInvalidate()從而形成一個回圈直到mScroller.computeScrollOffset()回傳false這個回圈才會停止
這樣我們就能實作彈性滑動,這是為什么呢,我們來看看mScroller.computeScrollOffset()方法
/**
* Call this when you want to know the new location. If it returns true,
* the animation is not yet finished.
*/
public boolean computeScrollOffset() {
if (mFinished) {
return false;
}
int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
//startScroll方法中的 mMode為SCROLL_MODE
//可以看到這里使用了插值器,關于插值器是什么可以去學習Android中的影片來了解
//這樣就能將本來要進行滑動的一大塊距離變成很多段小的距離,這樣我們就實作了彈性滑動
//每一次回圈可以將mCurrX mCurrY 這倆個值每一次增加一個比較小的值,然后在computeScroll中
//呼叫scrollTo(mScroller.getCurrX(), mScroller.getCurrY())就可以將要滑動的View滑動一個很小的距離
//只要View還沒有滑動到我們規定的位置,computeScrollOffset就會回傳true
//結果就是一次大滑動變成了很多次小滑動,體現的效果就是彈性滑動
if (timePassed < mDuration) {
switch (mMode) {
case SCROLL_MODE:
final float x = mInterpolator.getInterpolation(timePassed * mDurationReciprocal);
mCurrX = mStartX + Math.round(x * mDeltaX);
mCurrY = mStartY + Math.round(x * mDeltaY);
break;
case FLING_MODE:
final float t = (float) timePassed / mDuration;
final int index = (int) (NB_SAMPLES * t);
float distanceCoef = 1.f;
float velocityCoef = 0.f;
if (index < NB_SAMPLES) {
final float t_inf = (float) index / NB_SAMPLES;
final float t_sup = (float) (index + 1) / NB_SAMPLES;
final float d_inf = SPLINE_POSITION[index];
final float d_sup = SPLINE_POSITION[index + 1];
velocityCoef = (d_sup - d_inf) / (t_sup - t_inf);
distanceCoef = d_inf + (t - t_inf) * velocityCoef;
}
mCurrVelocity = velocityCoef * mDistance / mDuration * 1000.0f;
mCurrX = mStartX + Math.round(distanceCoef * (mFinalX - mStartX));
// Pin to mMinX <= mCurrX <= mMaxX
mCurrX = Math.min(mCurrX, mMaxX);
mCurrX = Math.max(mCurrX, mMinX);
mCurrY = mStartY + Math.round(distanceCoef * (mFinalY - mStartY));
// Pin to mMinY <= mCurrY <= mMaxY
mCurrY = Math.min(mCurrY, mMaxY);
mCurrY = Math.max(mCurrY, mMinY);
if (mCurrX == mFinalX && mCurrY == mFinalY) {
mFinished = true;
}
break;
}
}
else {
mCurrX = mFinalX;
mCurrY = mFinalY;
mFinished = true;
}
return true;
}
最后再看看View類中的computeScroll方法
發現是一個空方法
/**
* Called by a parent to request that a child update its values for mScrollX
* and mScrollY if necessary. This will typically be done if the child is
* animating a scroll using a {@link android.widget.Scroller Scroller}
* object.
*/
public void computeScroll() {
}
事件分發機制
我們點擊螢屏的事件會被抽象為MotionEvent類,事件分發機制也就是MotionEvent的分發程序,也就是說當一個MotionEvent產生后,系統需要把這個事件傳遞給一個具體個View,這個傳遞的程序就是事件分發,
當一個點擊事件產生后,他的傳遞程序遵循如下規則:
Activity—>Window—>View
首先我們來看Activity是怎么把點擊事件傳遞給Window的
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
從Activity中的dispatchTouchEvent方法中好像什么也看不出,我們來看看getWindow().superDispatchTouchEvent(ev),getWindow拿到的是一個mWindow物件
private Window mWindow;
public Window getWindow() {
return mWindow;
}
那么mWindow是什么呢?
可以再Activity中的attach方法中發現
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken)
{
...省略幾行代碼
mWindow = new PhoneWindow(this, window, activityConfigCallback);
...省略很多代碼
}
可知mWindow是一個PhoneWindow物件,那我們來看看PhoneWindow的superDispatchTouchEvent方法
// This is the top-level view of the window, containing the window decor.
private DecorView mDecor;
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
可以發現getWindow().superDispatchTouchEvent(ev)其實就是mDecor.superDispatchTouchEvent(event)
那么mDecor是什么呢?注釋說了,它是最高等級的View
當一個點擊事件產生后,他的傳遞程序遵循如下規則:
Activity—>Window—>View
那么,分析至此,點擊事件已經從Activity分發到了View
從以上的分析我們可以知道當點擊事件發生后,事件會首先傳遞到當前的Activity,這回呼叫Activity的dispatchTouchEvent方法,當然,具體的事件處理作業都是交由Activity的PhoneWindow來完成的,然后PhoneWindow再將事件處理作業交給DecorView,再有DecorView將事件處理交給根ViewGroup,所以下面我們從ViewGroup的dispatchTouchEvent開始分析,
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
......
// Handle an initial down.
//這個方法會在Actiondown事件到來時將FLAG_DISALLOW_INTERCEPT標志位重置,關于這個標志位有何用,我們后面分析
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
/**
這段代碼是用來判斷ViewGroup是否攔截這個事件的
可以看出,ViewGroup會在倆種情況下判斷是否要攔截這個事件,注意是判斷,不一定會攔截,如果不滿足這倆種條件,那么
intercepted = true ViewGroup就會直接攔截事件
那么是哪倆種條件呢?
1.actionMasked == MotionEvent.ACTION_DOWN 2.mFirstTouchTarget != null
那么mFirstTouchTarget是個什么東西呢?這個從后面的代碼可以看出如果點擊事件成功傳遞給了ViewGroup的子View,那么
mFirstTouchTarget就會賦值這個處理事件的子View
從這個if陳述句的判斷條件我們可知如果沒有子View來處理這個點擊事件,那么mFirstTouchTarget == null那么一個點擊事件的一序列事件(如actionup,actionmove)等都會交由ViewGroup處理
但是這里還有一種特殊情況,那就是FLAG_DISALLOW_INTERCEPT這個標志位,這個標志位是通過requestDisallowInteerceptTouchEvent來設定的,一般用于子View中,設定后,ViewGroup將無法攔截處理ACTION_DOWN之外的事件,為什么還能攔截ACTION_DOWN事件呢?通過之前的分析可知這時這個標志位會被重置
此外,我們查看原始碼發現onInterceptTouchEvent(ev)默認回傳false,這說明ViewGroup默認不攔截事件,如果想要ViewGroup攔截事件則要重寫onInterceptTouchEvent方法
*/
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
...
if (!canceled && !intercepted) {
...
/**
這里是遍歷ViewGroup的每一個子View,!child.canReceivePointerEvents()
|| !isTransformedTouchPointInView(x, y, child, null)這個條件是判斷點擊事件是否位于當前所判斷的View的范圍內和這個View是否正在播放影片,如果View滿足這倆個判斷條件中的一種就會執行continue陳述句開始判斷下一個子View直到找到一個符合條件的子View
*/
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
if (!child.canReceivePointerEvents()
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
/**
再來分析dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)這個方法
對于這個方法,如果傳入的child為null,那么回傳super.dispatchTouchEvent(event)
否則回傳child.dispatchTouchevent(event),這樣,點擊事件就由父View傳遞到了子View
*/
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
//如果點擊事件成功分發給了子View,就會通過這行代碼給mFirstTouchTarget賦值,對應了前面的分析
//具體實作可以查看addTouchTarget方法
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null) preorderedList.clear();
}
...
}
/**
mFirstTouchTarget==null有倆種條件,一種是沒有在ViewGroup中找到的合適的子View,還有一個情況就是找到了合適的子View,但是
child.dispatchTouchevent(event)回傳了false,從前面的分析我們可以直到這回導致mFirstTouchTarget不被賦值
*/
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
...
}
...
return handled;
}
接下來,我們來看看View的事件分發相關的原始碼
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
......
/**
從下面的代碼我們可以看出首先會判斷有沒有OnTouchListener,如果OnTouchListener的onTouch方法回傳true,那么result=true,onTouchEvent就不會被呼叫,從而我們可以知道OnTouchListener的優先級高于onTouchEvent,這樣做的好處是方便在外界處理事件
*/
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
......
return result;
}
再看看onTouchEvent
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
......
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
if (!clickable) {
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
}
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true, x, y);
}
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClickInternal();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
......
}
return true;
}
return false;
}
//從上面的代碼可以看出,只要View的CLICKABLE和LONG_CLICKABLE有一個為true,那么onTouchEvent()就會回傳true,CLICKABLE和LONG_CLICKABLE可以通過View的相關set方法來設定,對于一些控制元件像Button CLICKABLE屬性不用設定便具有接著在ACTION_UP事件中會呼叫performClicK方法
public boolean performClick() {
// We still need to call this method to handle the cases where performClick() was called
// externally, instead of through performClickInternal()
notifyAutofillManagerOnClick();
final boolean result;
final ListenerInfo li = mListenerInfo;
//可以看出,如果View設定了點擊事件,那么它的onClick方法就會執行
//則
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
notifyEnterOrExitForAutoFillIfNeeded(true);
return result;
}
綜合以上分析,我們可以知道點擊事件由上而下的傳遞規則,當點擊事件產生后會由Activity處理,傳遞給PhoneWindow,再傳遞給DecorView,最后傳遞給頂層的ViewGroup,對于根ViewGroup,點擊事件首先傳遞給它的dispatchTouchEvent,如果該ViewGroup的onIntercept方法放回true,則表示他要攔截這個事件,這個事件就會交由他的onTouchEvent處理,反則這個事件會傳遞給它的子View處理,如此傳遞下去,這個事件就會傳遞給最底層的View,如果最底層的View也不處理這個事件,那么這個事件又會一層層的往上傳,
關于為什么如果最底層的View不處理這個事件,那么這個事件為什么又會一層層的往上傳我之前一直沒能理解,搞了好久才懂,因此額外多說幾句關于這個的
對于 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))這個方法如果傳入的child為null,那么回傳super.dispatchTouchEvent(event),否則回傳child.dispatchTouchevent(event),這樣,點擊事件就由父View傳遞到了子View,但是如果child.dispatchTouchevent(event)回傳了false,那么mFirstTouchTarget就不會被賦值,那么mFirstTouchTarget == null就會執行
handled = dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);
通過對dispatchTransformedTouchEvent的分析我們可以知道此時就將點擊事件又由子View往上傳了!
滑動沖突處理
滑動沖突處理一般有倆種方法,一種是外部攔截法,還有一種是內部攔截法
外部攔截法
所謂的“外部攔截法“中的外部是指出現滑動沖突的這兩個布局的外層,我們知道,一個事件序列是由Parent View先獲取到的,如果Parent View不攔截事件那么才會交由子View去處理,既然是外層先獲知事件,那外層View根據自身情況來決定是否要攔截事件不就行了嗎?因此外部攔截法的實作是非常簡單的,大概思路如下:
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean intercepted = false;
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
intercepted = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (needIntercept) { // 這里根據需求判斷是否需要攔截
intercepted = true;
} else {
intercepted = false;
}
break;
}
case MotionEvent.ACTION_UP: {
intercepted = false;
break;
}
default:
break;
}
mLastXIntercept = x;
mLastYIntercept = y;
return intercepted;
}
內部攔截法
所謂的”內部攔截法“指的是對內部的View做文章,讓內部View決定是不是攔截事件,但是現在就有問題了,你怎么知道外部的View是不是要攔截事件啊??如果外部View把事件攔截了,內部的View豈不是連西北風都喝不到了?
別著急,Google官方當然有考慮到這種情況,在ViewGroup中有一個叫requestDisallowInterceptTouchEvent的方法(關于這個方法的原理已經在前面分析過了),這個方法接受一個boolean值,意思是是否要禁止ViewGroup攔截當前事件,如果是true的話那么該ViewGroup則無法對事件進行攔截,有了這個方法那我們就可以讓內部View大顯神通了,來看下內部攔截法的代碼:
public boolean dispatchTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
// 禁止parent攔截down事件
parent.requestDisallowInterceptTouchEvent(true);
break;
}
case MotionEvent.ACTION_MOVE: {
int deltaX = x - mLastX;
int deltaY = y - mLastY;
if (disallowParentInterceptTouchEvent) { // 根據需求條件來決定是否讓Parent View攔截事件,
parent.requestDisallowInterceptTouchEvent(false);
}
break;
}
case MotionEvent.ACTION_UP: {
break;
}
default:
break;
}
mLastX = x;
mLastY = y;
return super.dispatchTouchEvent(event);
}
解決ViewPager2的滑動沖突問題
關于ViewPager2的基本使用方法可以看這篇文章
https://zhpanvip.gitee.io/2019/12/14/24.Know%20about%20ViewPager2/
關于如何解決ViewPager2的滑動沖突問題,請看我寫的這篇文章:
View的繪制
首先介紹ViewRoot,ViewRoot對應于ViewRootImpl類,它是連接WindowManger和DecorView得紐帶,view的三大流程都是通過ViewRoot來完成的,當Activity被創建時,會將DecorView添加到Window中,同時創建ViewRootImpl類,然后將DecorView與ViewRootImpl建立關聯,
View的繪制流程從ViewRoot的performTraversals方法開始,performTraversals依次呼叫performMeasure performLayout 和
performDraw三個方法,這三個方法分別完成View的measure,layout,draw,其中在performMeasure中viewRoot會呼叫DecorView的measure方法,在measure方法中又會呼叫onMeasure方法,在onMeasure方法中會對所有子View進行Measure程序,對于performLayout 和 performDraw也是差不多的道理,如此就完成了整個View樹的遍歷,
理解MeasureSpec
首先來看看MeasureSpen的原始碼
/**
* A MeasureSpec encapsulates the layout requirements passed from parent to child.
* Each MeasureSpec represents a requirement for either the width or the height.
* A MeasureSpec is comprised of a size and a mode. There are three possible
* modes:
* <dl>
* <dt>UNSPECIFIED</dt>
* <dd>
* The parent has not imposed any constraint on the child. It can be whatever size
* it wants.
* </dd>
*
* <dt>EXACTLY</dt>
* <dd>
* The parent has determined an exact size for the child. The child is going to be
* given those bounds regardless of how big it wants to be.
* </dd>
*
* <dt>AT_MOST</dt>
* <dd>
* The child can be as large as it wants up to the specified size.
* </dd>
* </dl>
*
* MeasureSpecs are implemented as ints to reduce object allocation. This class
* is provided to pack and unpack the <size, mode> tuple into the int.
*/
public static class MeasureSpec {
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
/** @hide */
@IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
@Retention(RetentionPolicy.SOURCE)
public @interface MeasureSpecMode {}
/**
* Measure specification mode: The parent has not imposed any constraint
* on the child. It can be whatever size it wants.
*/
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
/**
* Measure specification mode: The parent has determined an exact size
* for the child. The child is going to be given those bounds regardless
* of how big it wants to be.
*/
public static final int EXACTLY = 1 << MODE_SHIFT;
/**
* Measure specification mode: The child can be as large as it wants up
* to the specified size.
*/
public static final int AT_MOST = 2 << MODE_SHIFT;
/**
* Creates a measure specification based on the supplied size and mode.
*
* The mode must always be one of the following:
* <ul>
* <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
* <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
* <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
* </ul>
*
* <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
* implementation was such that the order of arguments did not matter
* and overflow in either value could impact the resulting MeasureSpec.
* {@link android.widget.RelativeLayout} was affected by this bug.
* Apps targeting API levels greater than 17 will get the fixed, more strict
* behavior.</p>
*
* @param size the size of the measure specification
* @param mode the mode of the measure specification
* @return the measure specification based on size and mode
*/
public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
@MeasureSpecMode int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
/**
* Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
* will automatically get a size of 0. Older apps expect this.
*
* @hide internal use only for compatibility with system widgets and older apps
*/
@UnsupportedAppUsage
public static int makeSafeMeasureSpec(int size, int mode) {
if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
return 0;
}
return makeMeasureSpec(size, mode);
}
/**
* Extracts the mode from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the mode from
* @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
* {@link android.view.View.MeasureSpec#AT_MOST} or
* {@link android.view.View.MeasureSpec#EXACTLY}
*/
@MeasureSpecMode
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
/**
* Extracts the size from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the size from
* @return the size in pixels defined in the supplied measure specification
*/
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
static int adjust(int measureSpec, int delta) {
final int mode = getMode(measureSpec);
int size = getSize(measureSpec);
if (mode == UNSPECIFIED) {
// No need to adjust size for UNSPECIFIED mode.
return makeMeasureSpec(size, UNSPECIFIED);
}
size += delta;
if (size < 0) {
Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
") spec: " + toString(measureSpec) + " delta: " + delta);
size = 0;
}
return makeMeasureSpec(size, mode);
}
/**
* Returns a String representation of the specified measure
* specification.
*
* @param measureSpec the measure specification to convert to a String
* @return a String with the following format: "MeasureSpec: MODE SIZE"
*/
public static String toString(int measureSpec) {
int mode = getMode(measureSpec);
int size = getSize(measureSpec);
StringBuilder sb = new StringBuilder("MeasureSpec: ");
if (mode == UNSPECIFIED)
sb.append("UNSPECIFIED ");
else if (mode == EXACTLY)
sb.append("EXACTLY ");
else if (mode == AT_MOST)
sb.append("AT_MOST ");
else
sb.append(mode).append(" ");
sb.append(size);
return sb.toString();
}
}
MeasureSpec是一個32位int值,高2位表示SpecMode,低30位表示SpenSize,MeasureSpec將SpecMode和SpecSize打包成一個int值來避免過多的物件記憶體分配,并且MeasureSpen提供了打包和解包的操作,
View的MeasureSpec是怎么產生的
View的MeasureSpec與其LayoutParams及它的父View有關,為什么View的MeasureSpec與其LayoutParams及它的父View有關呢?帶著這個問題我們去查看原始碼
首先從View的onMeasure方法開始
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
setMeasuredDimension方法會設定View的寬高,我們來看getDefaultSize是怎么實作的
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
可以看到其實就是把onMeasure中提供的Spec引數進行解包后根據不同的規則得到對應的值,
同時我們可以發現
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
都是讓result = specSize;
這也說明直接繼承View的自定義控制元件需要重寫onMeasure方法并設定wrap_content時的大小,否則使用warp_content等同于使用match_parent.
通過以上的分析我們可以知道 View的寬高和onMeasure中傳入的int widthMeasureSpec, int heightMeasureSpec倆個引數有關,而這倆個引數是View的父View傳入的,我們來看看父View關于這個的原始碼
protected void measureChildWithMargins(View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
+ heightUsed, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
通過這部分原始碼我們的問題就解決了為什么View的MeasureSpec與其LayoutParams及它的父View有關這個問題,可以看到getChildMeasureSpec這個方法傳入的是父View的MeasureSpec和子View的LayoutParams.
接下來咱們再看看子View的MeasureSpec具體是怎么生成的,打開getChildMeasureSpec的原始碼
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
int size = Math.max(0, specSize - padding);
int resultSize = 0;
int resultMode = 0;
switch (specMode) {
// Parent has imposed an exact size on us
case MeasureSpec.EXACTLY:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size. So be it.
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size. It can't be
// bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent has imposed a maximum size on us
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
// Child wants a specific size... so be it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size, but our size is not fixed.
// Constrain child to not be bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size. It can't be
// bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent asked to see how big we want to be
case MeasureSpec.UNSPECIFIED:
if (childDimension >= 0) {
// Child wants a specific size... let him have it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size... find out how big it should
// be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size.... find out how
// big it should be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
//noinspection ResourceType
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
可以將上面的代碼總結成一張表:
ViewGroup的measure程序
對于ViewGroup來說,除了完成自己的measure程序以外,還會遍歷去呼叫所有子View的measure方法,各個子元素在遞回去執行這個程序,ViewGroup沒有onMeasure方法,但是它提供了一個叫measureChildren的方法:
/**
* Ask one of the children of this view to measure itself, taking into
* account both the MeasureSpec requirements for this view and its padding
* and margins. The child must have MarginLayoutParams The heavy lifting is
* done in getChildMeasureSpec.
*
* @param child The child to measure
* @param parentWidthMeasureSpec The width requirements for this view
* @param widthUsed Extra space that has been used up by the parent
* horizontally (possibly by other children of the parent)
* @param parentHeightMeasureSpec The height requirements for this view
* @param heightUsed Extra space that has been used up by the parent
* vertically (possibly by other children of the parent)
*/
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
final int size = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < size; ++i) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
}
}
ViewGroup沒有定義其具體的測量程序這是因為ViewGroup是一個抽象類,其測量程序的onMeasure方法需要各個子類去具體實作,
ViewGroup的layout程序
Layout程序就是ViewGroup將其子View根據測量值來將其擺放在自己的空間中
layout方法確定view自身的位置而onLayout方法則會確定ViewGroup所有子View的位置
View的layout和onLayout方法
@Override
public final void layout(int l, int t, int r, int b) {
if (!mSuppressLayout && (mTransition == null || !mTransition.isChangingLayout())) {
if (mTransition != null) {
mTransition.layoutChange(this);
}
super.layout(l, t, r, b);
} else {
// record the fact that we noop'd it; request layout when transition finishes
mLayoutCalledWhileSuppressed = true;
}
}
@Override
protected abstract void onLayout(boolean changed,
int l, int t, int r, int b);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/272522.html
標籤:其他
下一篇:最全Android度量單位px dp(dip) ppi dpi sp pt的區別(螢屏尺寸,螢屏解析度,螢屏兼容,螢屏適配)
