重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
今天就跟大家聊聊有關(guān)Android中怎么利用ViewGroup自定義布局,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
首先,如果是一個(gè) LinearLayout 那么當(dāng)設(shè)置 wrap_content 時(shí),他就會(huì)以子空間中最寬的那個(gè)為它的寬度。同時(shí)在高度方面會(huì)是所有子控件高度的總和。所以我們先寫(xiě)兩個(gè)方法,分別用于測(cè)量 ViewGroup 的寬度和高度。
private int getMaxWidth(){ int count = getChildCount(); int maxWidth = 0; for (int i = 0 ; i < count ; i ++){ int currentWidth = getChildAt(i).getMeasuredWidth(); if (maxWidth < currentWidth){ maxWidth = currentWidth; } } return maxWidth; } private int getTotalHeight(){ int count = getChildCount(); int totalHeight = 0; for (int i = 0 ; i < count ; i++){ totalHeight += getChildAt(i).getMeasuredHeight(); } return totalHeight; }
對(duì)于 ViewGroup 而言我們可以粗略的分為兩種模式:固定長(zhǎng)寬模式(match_parent),自適應(yīng)模式(wrap_content),根據(jù)這兩種模式,就可以對(duì) ViewGroup 的繪制進(jìn)行劃分。這里關(guān)于 measureChildren 這個(gè)方法,他是用于將所有的子 View 進(jìn)行測(cè)量,這會(huì)觸發(fā)每個(gè)子 View 的 onMeasure 函數(shù),但是大家要注意要與 measureChild 區(qū)分,measureChild 是對(duì)單個(gè) view 進(jìn)行測(cè)量
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); measureChildren(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); int heightMode= MeasureSpec.getMode(heightMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST){ int groupWidth = getMaxWidth(); int groupHeight= getTotalHeight(); setMeasuredDimension(groupWidth, groupHeight); }else if (widthMode == MeasureSpec.AT_MOST){ setMeasuredDimension(getMaxWidth(), height); }else if (heightMode == MeasureSpec.AT_MOST){ setMeasuredDimension(width, getTotalHeight()); } }
重寫(xiě) onLayout
整完上面這些東西,我們的布局大小七十九已經(jīng)出來(lái)了,然我們?cè)诨顒?dòng)的布局文件里面加上它,并添加上幾個(gè)子 View 然后運(yùn)行一下,先看看效果:
運(yùn)行效果如下:
我們看見(jiàn)布局出來(lái)了,大小好像也沒(méi)啥問(wèn)題,但是子 View 呢??! 這么沒(méi)看見(jiàn)子 View 在看看代碼,系統(tǒng)之前然我們重寫(xiě)的 onLayout() 還是空著的呀!!也就是說(shuō),子 View 的大小和位置根本就還沒(méi)有進(jìn)行過(guò)設(shè)定!讓我們來(lái)重寫(xiě)下 onLayout() 方法。
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int count = getChildCount(); int currentHeight = 0; for (int i = 0 ; i < count ; i++){ View view = getChildAt(i); int height = view.getMeasuredHeight(); int width = view.getMeasuredWidth(); view.layout(l, currentHeight, l + width, currentHeight + height); currentHeight += height; } }
看完上述內(nèi)容,你們對(duì)Android中怎么利用ViewGroup自定義布局有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。