溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么從自定義ViewGroup看Layout的作用

發(fā)布時(shí)間:2021-06-22 14:05:28 來(lái)源:億速云 閱讀:121 作者:chen 欄目:web開(kāi)發(fā)

這篇文章主要介紹“怎么從自定義ViewGroup看Layout的作用”,在日常操作中,相信很多人在怎么從自定義ViewGroup看Layout的作用問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”怎么從自定義ViewGroup看Layout的作用”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

前言

上次我們說(shuō)到View的Mearsure流程,今天接著說(shuō)說(shuō)layout。

關(guān)于layout,很多朋友知道它是負(fù)責(zé)布局的,那么具體是怎么布局的?viewGroup和view的layout方法又有什么不同?一起來(lái)看看吧。

View layout方法

首先,還是從ViewRootImpl說(shuō)起,界面的繪制會(huì)觸發(fā)performMeasure、performLayout方法,而在performLayout方法中就會(huì)調(diào)用mView的layout方法開(kāi)始一層層View的布局工作。

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,            int desiredWindowHeight) {                final View host = mView;        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());    }

mView我們都知道了,就是頂層View——DecorView,那么就進(jìn)去看看DecorView的layout方法:

不好意思,DecorView中并沒(méi)有l(wèi)ayout方法...

所以,我們直接看看View的layout方法:

public void layout(int l, int t, int r, int b) {         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);        }    }     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {    }
  • 首先,方法傳入了四個(gè)參數(shù),分別代表view的左、上、下、右四個(gè)值。

  • 然后通過(guò)setOpticalFrame方法或者setFrame方法判斷布局參數(shù)是否改變。

具體判斷過(guò)程就是通過(guò)老的上下左右值和新的上下左右值進(jìn)行比較,邏輯就在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;              // Remember our drawn bit             int drawn = mPrivateFlags & PFLAG_DRAWN;              int oldWidth = mRight - mLeft;             int oldHeight = mBottom - mTop;             int newWidth = right - left;             int newHeight = bottom - top;             boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);              // Invalidate our old position             invalidate(sizeChanged);              mLeft = left;             mTop = top;             mRight = right;             mBottom = bottom;             mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);         }         return changed;     }

如果上下左右有一個(gè)參數(shù)值發(fā)生了改變,就說(shuō)明這個(gè)View的布局發(fā)生了改變,然后重新計(jì)算View的寬度高度(newWidth、newHeight),并賦值了View新的上下左右參數(shù)值。

在這個(gè)layout方法中主要涉及到了四個(gè)參數(shù):mLeft、mTop、mBottom、mRight,分別代表了View的左坐標(biāo)、上坐標(biāo)、下坐標(biāo)和右坐標(biāo),你可以把View理解為一個(gè)矩形,確定了這四個(gè)值,就能確定View矩形的四個(gè)頂點(diǎn)值,也就能確定View在畫布中的具體位置。

所以,layout方法到底干了啥?

就是傳入上下左右值、然后賦值上下左右值、完畢。

然后我們就可以根據(jù)這些值獲取View的一系列參數(shù),比如View寬度:

public final int getWidth() {       return mRight - mLeft;   }

至此,View的layout方法就結(jié)束了,主要就是通過(guò)對(duì)上下左右參數(shù)的賦值完成對(duì)View的布局,非常簡(jiǎn)單。

下面看看ViewGroup。

ViewGroup layout方法

@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 {            mLayoutCalledWhileSuppressed = true;        }    }

額,還是調(diào)用到View的layout方法,難道說(shuō)ViewGroup和View的布局過(guò)程是一樣的,就是確定了本身的位置?

那ViewGroup的子View怎么辦呢?不急,我們剛才說(shuō)layout方法的時(shí)候還漏了一個(gè)onLayout方法,只不過(guò)這個(gè)方法在View里面是空實(shí)現(xiàn),而到了ViewGroup中變成了一個(gè)抽象方法:

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

也就是任何ViewGroup都必須實(shí)現(xiàn)這個(gè)方法,來(lái)完成對(duì)子View的布局?jǐn)[放。

具體的布局?jǐn)[放邏輯就是在onLayout方法中一個(gè)個(gè)調(diào)用子View的layout方法,然后完成每個(gè)子View的布局,最終完成繪制工作。

接下來(lái)我們就來(lái)自己實(shí)現(xiàn)一個(gè)垂直線性布局(類似LinearLayout),正好復(fù)習(xí)下上一節(jié)的onMearsure和這一節(jié)的onLayout。

自定義垂直布局VerticalLayout

首先,我們要確定我們這個(gè)自定義ViewGroup的作用,是類似垂直方向的LinearLayout功能,在該ViewGroup下的子View可以按垂直線性順序依次往下排放。我們給它起個(gè)名字叫VerticalLayout~

繼承ViewGroup

首先,我們這個(gè)布局肯定要繼承自ViewGroup,并且實(shí)現(xiàn)相應(yīng)的構(gòu)造方法:

public class VerticalLayout : ViewGroup {      constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0) : super(         context,         attrs,         defStyleAttr     )      constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {     } }

重寫generateLayoutParams方法

自定義ViewGroup還需要重寫的一個(gè)方法是generateLayoutParams,這一步是為了讓我們的ViewGroup支持Margin,后續(xù)我們就可以通過(guò)MarginLayoutParams來(lái)獲取子View的Margin值。

override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams? {       return MarginLayoutParams(context, attrs)   }

重寫測(cè)量方法onMeasure

然后,我們需要對(duì)我們的布局進(jìn)行測(cè)量,也就是重寫onMeasure方法。

在該方法中,我們需要對(duì)我們的布局進(jìn)行測(cè)量,并且將測(cè)量好的寬高傳入setMeasuredDimension方法,完成測(cè)量。

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight)

之前我們說(shuō)過(guò),onMeasure方法會(huì)傳進(jìn)來(lái)兩個(gè)參數(shù),widthMeasureSpec和heightMeasureSpec。

里面包含了父View根據(jù)當(dāng)前View的LayoutParams和父View的測(cè)量規(guī)格進(jìn)行計(jì)算,得出的對(duì)當(dāng)前View期望的測(cè)量模式和測(cè)量大小:

  • 當(dāng)測(cè)量模式為MeasureSpec.EXACTLY

也就是當(dāng)寬或者高為確定值時(shí),那么當(dāng)前布局View的寬高也就是設(shè)定為父View給我們?cè)O(shè)置好的測(cè)量大小即可。比如寬為400dp,那么我們無(wú)需重新測(cè)量直接調(diào)用setMeasuredDimension傳入這個(gè)固定值即可。

  • 當(dāng)測(cè)量模式為MeasureSpec.AT_MOST 或者 UNSPECIFIED:

這時(shí)候,說(shuō)明父View對(duì)當(dāng)前View的要求不固定,是可以為任意大小或者不超過(guò)最大值的情況,比如設(shè)置這個(gè)VerticalLayout的高度為wrap_content。那么我們就必須重新進(jìn)行高度測(cè)量了,因?yàn)橹挥形覀冊(cè)O(shè)計(jì)者知道這個(gè)自適應(yīng)高度需要怎么計(jì)算。具體就是VerticalLayout是一個(gè)垂直線性布局,所以高度很自然就是所有子View的高度之和。

至此,onMeasure方法的邏輯也基本摸清了:

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {         super.onMeasure(widthMeasureSpec, heightMeasureSpec)         //獲取寬高的測(cè)量模式和測(cè)量大小         val widthMode = MeasureSpec.getMode(widthMeasureSpec)         val heightMode = MeasureSpec.getMode(heightMeasureSpec)         val sizeWidth = MeasureSpec.getSize(widthMeasureSpec)         val sizeHeight = MeasureSpec.getSize(heightMeasureSpec)          var mHeight = 0         var mWidth = 0          //遍歷子View,獲取總高度         for (i in 0 until childCount) {             val childView = getChildAt(i)             //測(cè)量子View的寬和高             measureChild(childView, widthMeasureSpec, heightMeasureSpec)             val lp = childView.layoutParams as MarginLayoutParams             val childWidth = childView.measuredWidth + lp.leftMargin + lp.rightMargin             val childHeight = childView.measuredHeight + lp.topMargin + lp.bottomMargin              //計(jì)算得出最大寬度             mWidth = Math.max(mWidth, childWidth)             //累計(jì)計(jì)算高度             mHeight += childHeight         }          //設(shè)置寬高         setMeasuredDimension(             if (widthMode == MeasureSpec.EXACTLY) sizeWidth else mWidth,             if (heightMode == MeasureSpec.EXACTLY) sizeHeight else mHeight         )     }

主要的邏輯就是遍歷子View,得出VerticalLayout的實(shí)際寬高:

最終ViewGroup的高 = 所有子View的 (高 + margin值)

最終ViewGroup的寬 = 最大子View的 (寬 + margin值)

最后調(diào)用setMeasuredDimension 根據(jù)測(cè)量模式 傳入寬高。

重寫布局方法onLayout

上文說(shuō)過(guò),作為一個(gè)ViewGroup,必須重寫onLayout方法,來(lái)保證子View的正常布局?jǐn)[放。

垂直線性布局VerticalLayout亦是如此,那么在這個(gè)布局中onLayout方法的關(guān)鍵邏輯又是什么呢?

還是那句話,確定位置,也就是確定左、上、右、下四個(gè)參數(shù)值,而在VerticalLayout中,最關(guān)鍵的參數(shù)就是這個(gè)上,也就是top值。

每個(gè)View的top值必須是上一個(gè)View的bottom值,也就是接著上一個(gè)View進(jìn)行擺放,這樣才會(huì)是垂直線性的效果,所以我們需要做的就是動(dòng)態(tài)計(jì)算每個(gè)View的top值,其實(shí)也就是不斷累加View的高度,作為下一個(gè)View的top值。

override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {         var childWidth = 0         var childHeight = 0         var childTop = 0         var lp: MarginLayoutParams          //遍歷子View,布局每個(gè)子View         for (i in 0 until childCount) {             val childView = getChildAt(i)             childHeight = childView.measuredHeight             childWidth = childView.measuredWidth             lp = childView.layoutParams as MarginLayoutParams              //累計(jì)計(jì)算top值             childTop += lp.topMargin              //布局子View             childView.layout(                 lp.leftMargin,                 childTop,                 lp.leftMargin + childWidth,                 childTop + childHeight             );              childTop += childHeight + lp.bottomMargin         }     }

邏輯還是挺簡(jiǎn)單的,

left是固定的子View的leftMargin。

top是累加計(jì)算的子View的高度 + Margin值。

right是left + 子View的寬度。

bottom是top + 子View的高度。

最后調(diào)用子View的layout方法,對(duì)每個(gè)子View進(jìn)行布局。

大功告成,最后看看我們這個(gè)自定義垂直線性布局的效果吧~

效果展示

<com.panda.studynote3.VerticalLayout         android:layout_width="wrap_content"         android:layout_height="wrap_content">          <TextView             android:layout_width="100dp"             android:layout_height="100dp"             android:text="啦啦啦"             android:textSize="20sp"             android:textColor="@color/white"             android:background="@color/design_default_color_primary"             />          <TextView             android:layout_width="300dp"             android:layout_height="200dp"             android:layout_marginTop="20dp"             android:background="@color/cardview_dark_background"             android:textSize="20sp"             android:textColor="@color/white"             android:text="你好啊"             />          <TextView             android:layout_width="140dp"             android:layout_height="100dp"             android:text="嘻嘻"             android:layout_marginLeft="10dp"             android:layout_marginTop="10dp"             android:textSize="20sp"             android:gravity="center"             android:textColor="@color/black"             android:background="@color/teal_200"             />      </com.panda.studynote3.VerticalLayout>

怎么從自定義ViewGroup看Layout的作用

到此,關(guān)于“怎么從自定義ViewGroup看Layout的作用”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI