Android實現(xiàn)簡單的自定義ViewGroup流式布局
前言
前面幾篇我們簡單的復(fù)習(xí)了一下自定義 View 的測量與繪制,并且回顧了常見的一些事件的處理方式。
那么如果我們想自定義 ViewGroup 的話,它和自定義View又有什么區(qū)別呢?其實我們把 ViewGroup 當(dāng)做 View 來用的話也不是不可以。但是既然我們用到了容器 ViewGroup 當(dāng)時是想用它的一些特殊的特性了。
比如 ViewGroup 的測量,ViewGroup的布局,ViewGroup的繪制。
- ViewGroup的測量:與 View 的測量不同,ViewGroup 的測量會遍歷子 View ,獲取子 View 的大小,從而決定自己的大小。當(dāng)然我們也可以通過指定的模式來指定自身的大小。
- ViewGroup的布局:這個是 ViewGroup 核心與常用的功能。找到對于的子View 布局到指定的位置。
- ViewGroup的繪制:一般我們不會重寫這個方法,因為一般來說它本身不需要繪制,并且當(dāng)我們沒有設(shè)置ViewGroup的背景的時候,onDraw()方法都不會被調(diào)用,一般來說 ViewGroup 只是會使用 dispatchDraw()方法來繪制其子View,其過程同樣是通過遍歷所有子View,并調(diào)用子View的繪制方法來完成繪制工作。
下面我們一起復(fù)習(xí)一下ViewGroup的測量布局方式。我們以入門級的 FlowLayout 為例,看看流式布局是如何測量與布局的。
話不多說,Let's go
一、基本的測量與布局
我們先回顧一下ViewGroup的
一個經(jīng)典的ViewGroup測量是怎樣實現(xiàn)?一般來說,最簡單的測量如下:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
for(int i = 0; i < getChildCount(); i++){
View childView = getChildAt(i);
measureChild(childView,widthMeasureSpec,heightMeasureSpec);
}
}或者我們直接使用封裝之后的默認(rèn)方法
measureChildren(widthMeasureSpec,heightMeasureSpec);
其內(nèi)部也是遍歷子View來實現(xiàn)的。當(dāng)然如果有自定義的一些寬高測量規(guī)則,就不能使用這個方法,就需要自己遍歷找到View自定義實現(xiàn)了。
需要注意的是,這里我們測量子布局傳遞的 widthMeasureSpec 和 heightMeasureSpec 是父布局的測量模式。
當(dāng)父布局設(shè)置為固定寬度的時候,子View是不能超過這個寬度的,比如父控件設(shè)置為match_parent,自定義View無論是match_parent 還是 wrap_content 都是一樣的,充滿整個父控件。
相當(dāng)于父布局調(diào)用子控件的onMeasure方法的時候告訴子控件,我就這么大,你看著辦,不能超過它。
而父布局傳遞的是自適應(yīng)AT_MOST模式,那么就是由子View來決定父布局的寬高。
相當(dāng)于父布局調(diào)用子控件的onMeasure方法的時候問子控件,我也不知道我多大,你需要多大的位置?我又需要多大的地方才能容納你?
其實也很好理解。那么一個經(jīng)典的ViewGroup布局又是怎樣實現(xiàn)?重寫 onLayout 并且遍歷拿到每一個View,進(jìn)行Layout操作。
比如如下的代碼,我們每一個View的高度設(shè)置為固定高度,并且垂直排列,類似一個ListView 的布局:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
//設(shè)置子View的高度
MarginLayoutParams params = (MarginLayoutParams) getLayoutParams();
params.height = mFixedHeight * childCount;
setLayoutParams(params);
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
child.layout(l, i * mFixedHeight, r, (i + 1) * mFixedHeight);
}
}
}注意我們 onLayout() 的參數(shù)
展示的效果就是這樣:

二、流式的布局的layout
首先我們先不管測量,我們先指定ViewGroup的寬高為固定寬高,指定為match_parent。我們先做布局的操作:

我們自定義 ViewGroup 中重寫測量與布局的方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec,heightMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
/**
* @param changed 當(dāng)前ViewGroup的尺寸或者位置是否發(fā)生了改變
* @param l,t,r,b 當(dāng)前ViewGroup相對于父控件的坐標(biāo)位置,
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int mViewGroupWidth = getMeasuredWidth(); //當(dāng)前ViewGroup的總寬度
int layoutChildViewCurX = l; //當(dāng)前繪制View的X坐標(biāo)
int layoutChildViewCurY = t; //當(dāng)前繪制View的Y坐標(biāo)
int childCount = getChildCount(); //子控件的數(shù)量
//遍歷所有子控件,并在其位置上繪制子控件
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
//子控件的寬和高
int width = childView.getMeasuredWidth();
int height = childView.getMeasuredHeight();
//如果剩余控件不夠,則移到下一行開始位置
if (layoutChildViewCurX + width > mViewGroupWidth) {
layoutChildViewCurX = l;
//如果換行,則需要修改當(dāng)前繪制的高度位置
layoutChildViewCurY += height;
}
//執(zhí)行childView的布局與繪制(右和下的位置加上自身的寬高即可)
childView.layout(layoutChildViewCurX, layoutChildViewCurY, layoutChildViewCurX + width, layoutChildViewCurY + height);
//布局完成之后,下一次繪制的X坐標(biāo)需要加上寬度
layoutChildViewCurX += width;
}
}最后我們就能得到對應(yīng)的換行效果,如下:

通過上面我們的基礎(chǔ)學(xué)習(xí),我們應(yīng)該能理解這樣的布局方式,跟上面的基礎(chǔ)布局方式相比,就是多了一個 layoutChildViewCurX 和 layoutChildViewCurY 。關(guān)于其它的邏輯這里已經(jīng)注釋的非常清楚了。
但是這樣的效果好丑,我們加上間距 margin 試試?

并沒有效果,其實是內(nèi)部 View 的 LayoutParams 就不支持 margin,我們需要定義一個內(nèi)部類繼承 ViewGroup.MarginLayoutParams,并重寫generateLayoutParams() 方法。
//要使子控件的margin屬性有效必須繼承此LayoutParams,內(nèi)部還可以定制一些別的屬性
public static class LayoutParams extends MarginLayoutParams {
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(ViewGroup.LayoutParams layoutParams) {
super(layoutParams);
}
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new ViewGroup2.LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}然后修改一下代碼,在 layout 子布局的時候我們手動的把 margin 加上。
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int mViewGroupWidth = getMeasuredWidth(); //當(dāng)前ViewGroup的總寬度
int layoutChildViewCurX = l; //當(dāng)前繪制View的X坐標(biāo)
int layoutChildViewCurY = t; //當(dāng)前繪制View的Y坐標(biāo)
int childCount = getChildCount(); //子控件的數(shù)量
//遍歷所有子控件,并在其位置上繪制子控件
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
//子控件的寬和高
int width = childView.getMeasuredWidth();
int height = childView.getMeasuredHeight();
final LayoutParams lp = (LayoutParams) childView.getLayoutParams();
//如果剩余控件不夠,則移到下一行開始位置
if (layoutChildViewCurX + width + lp.leftMargin + lp.rightMargin > mViewGroupWidth) {
layoutChildViewCurX = l;
//如果換行,則需要修改當(dāng)前繪制的高度位置
layoutChildViewCurY += height + lp.topMargin + lp.bottomMargin;
}
//執(zhí)行childView的布局與繪制(右和下的位置加上自身的寬高即可)
childView.layout(
layoutChildViewCurX + lp.leftMargin,
layoutChildViewCurY + lp.topMargin,
layoutChildViewCurX + width + lp.leftMargin + lp.rightMargin,
layoutChildViewCurY + height + lp.topMargin + lp.bottomMargin);
//布局完成之后,下一次繪制的X坐標(biāo)需要加上寬度
layoutChildViewCurX += width + lp.leftMargin + lp.rightMargin;
}
}此時的效果就能生效了:

三、流式的布局的Measure
前面的設(shè)置我們都是使用的寬高 match_parent。那我們修改 ViewGroup 的高度為 wrap_content ,能實現(xiàn)高度自適應(yīng)嗎?

這...并不是我們想要的效果。并沒有自適應(yīng)高度。因為我們沒有寫測量的邏輯。
我們想一下,如果我們的寬度是固定的,想要高度自適應(yīng),那么我們就需要測量每一個子View的高度,計算出對應(yīng)的高度,當(dāng)換行之后我們再加上行的高度。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int sizeWidth = MeasureSpec.getSize(widthMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft();
final int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
final int sizeHeight = MeasureSpec.getSize(heightMeasureSpec) - this.getPaddingTop() - this.getPaddingBottom();
final int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
if (modeWidth == MeasureSpec.EXACTLY && modeHeight == MeasureSpec.EXACTLY) {
measureChildren(widthMeasureSpec, heightMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} else if (modeWidth == MeasureSpec.EXACTLY && modeHeight == MeasureSpec.AT_MOST) {
int layoutChildViewCurX = this.getPaddingLeft();
int totalControlHeight = 0;
for (int i = 0; i < getChildCount(); i++) {
final View childView = this.getChildAt(i);
if (childView.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) childView.getLayoutParams();
childView.measure(
getChildMeasureSpec(widthMeasureSpec, this.getPaddingLeft() + this.getPaddingRight(), lp.width),
getChildMeasureSpec(heightMeasureSpec, this.getPaddingTop() + this.getPaddingBottom(), lp.height)
);
int width = childView.getMeasuredWidth();
int height = childView.getMeasuredHeight();
if (totalControlHeight == 0) {
totalControlHeight = height + lp.topMargin + lp.bottomMargin;
}
//如果剩余控件不夠,則移到下一行開始位置
if (layoutChildViewCurX + width + lp.leftMargin + lp.rightMargin > sizeWidth) {
layoutChildViewCurX = this.getPaddingLeft();
totalControlHeight += height + lp.topMargin + lp.bottomMargin;
}
layoutChildViewCurX += width + lp.leftMargin + lp.rightMargin;
}
//最后確定整個布局的高度和寬度
int cachedTotalWith = resolveSize(sizeWidth, widthMeasureSpec);
int cachedTotalHeight = resolveSize(totalControlHeight, heightMeasureSpec);
this.setMeasuredDimension(cachedTotalWith, cachedTotalHeight);
}寬度固定和高度自適應(yīng)的情況下,我們是這么處理的。計算出子View的總高度,然后設(shè)置 setMeasuredDimension 為ViewGroup的測量寬度和子View的總高度。即為最終 ViewGroup 的寬高。

這樣我們就能實現(xiàn)高度的自適應(yīng)了。那么寬度能不能自適應(yīng)呢?
當(dāng)然可以,我們只需要記錄每一行的寬度,然后最終 setMeasuredDimension 的時候傳入所有行中的最大寬度,就是 ViewGroup 的最終寬度,而高度的計算是和上面的方式一樣的。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
...
else if (modeWidth == MeasureSpec.AT_MOST && modeHeight == MeasureSpec.AT_MOST) {
//如果寬高都是Wrap-Content
int layoutChildViewCurX = this.getPaddingLeft();
//總寬度和總高度
int totalControlWidth = 0;
int totalControlHeight = 0;
//由于寬度是非固定的,所以用一個List接收每一行的最大寬度
List<Integer> lineLenghts = new ArrayList<>();
for (int i = 0; i < getChildCount(); i++) {
final View childView = this.getChildAt(i);
if (childView.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) childView.getLayoutParams();
childView.measure(
getChildMeasureSpec(widthMeasureSpec, this.getPaddingLeft() + this.getPaddingRight(), lp.width),
getChildMeasureSpec(heightMeasureSpec, this.getPaddingTop() + this.getPaddingBottom(), lp.height)
);
int width = childView.getMeasuredWidth();
int height = childView.getMeasuredHeight();
if (totalControlHeight == 0) {
totalControlHeight = height + lp.topMargin + lp.bottomMargin;
}
//如果剩余控件不夠,則移到下一行開始位置
if (layoutChildViewCurX + width + lp.leftMargin + lp.rightMargin > sizeWidth) {
lineLenghts.add(layoutChildViewCurX);
layoutChildViewCurX = this.getPaddingLeft();
totalControlHeight += height + lp.topMargin + lp.bottomMargin;
}
layoutChildViewCurX += width + lp.leftMargin + lp.rightMargin;
}
//計算每一行的寬度,選出最大值
YYLogUtils.w("每一行的寬度 :" + lineLenghts.toString());
totalControlWidth = Collections.max(lineLenghts);
YYLogUtils.w("選出最大寬度 :" + totalControlWidth);
//最后確定整個布局的高度和寬度
int cachedTotalWith = resolveSize(totalControlWidth, widthMeasureSpec);
int cachedTotalHeight = resolveSize(totalControlHeight, heightMeasureSpec);
this.setMeasuredDimension(cachedTotalWith, cachedTotalHeight);
}
}為了效果,我們把第一行的最后一個View寬度多一點,方便查看效果。

這樣就可以得到ViewGroup自適應(yīng)的寬度和高度了。并不復(fù)雜對不對!
后記
這樣是不是就能實現(xiàn)一個簡單的流式布局了呢?當(dāng)然這些只是為方便學(xué)習(xí)和理解,真正的實戰(zhàn)中并不推薦直接這樣使用,因為內(nèi)部還有一些兼容的邏輯沒處理,一些邏輯沒有封裝,屬性沒有抽取。甚至連每一個View的高度,和每一行的最大高度也沒有處理,其實這樣健壯性并不好。
以上就是Android實現(xiàn)簡單的自定義ViewGroup流式布局的詳細(xì)內(nèi)容,更多關(guān)于Android ViewGroup流式布局的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android Support Annotations資料整理
這篇文章主要介紹了Android Support Annotations資料整理的相關(guān)資料,需要的朋友可以參考下2017-05-05
Android4.2中全屏或者取消標(biāo)題欄的方法總結(jié)
有的時候我們會看到,會先出現(xiàn)標(biāo)題欄,然后再消失,因為我們只是在activity的oncreate方法中定義的,其他實現(xiàn)方法如下,感興趣的朋友可以了解下哈2013-06-06
Android UI控件RatingBar實現(xiàn)自定義星星評分效果
這篇文章主要為大家詳細(xì)介紹了Android UI控件RatingBar實現(xiàn)自定義星星評分效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02
關(guān)于Android中ListView嵌套GridView的問題
在Android開發(fā)的過程中可能需要用到listview嵌套gridview的場景,但是在嵌套過程中也許會遇到問題,我們下面一起來看看是什么問題以及如何解決。2016-08-08
Android仿微信雷達(dá)掃描效果的實現(xiàn)方法
最近看了一個視頻講了一種微信雷達(dá)掃描的實現(xiàn)方案,借鑒了一下,自己也寫一個玩玩,所以下面這篇文章主要給大家介紹了利用Android模仿微信雷達(dá)掃描效果的實現(xiàn)方法,需要的朋友可以參考借鑒,下面來一起看看吧。2017-06-06
實例講解Android應(yīng)用開發(fā)中Fragment生命周期的控制
這篇文章主要介紹了Android應(yīng)用開發(fā)中Fragment生命周期的控制,Fragment依賴于Activity,所以生命周期方面也受Activity的影響,需要的朋友可以參考下2016-02-02
ComposeDesktop開發(fā)桌面端多功能APK工具
這篇文章主要為大家介紹了ComposeDesktop開發(fā)桌面端多功能APK工具實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07

