Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 ViewGroup 完整實戰:從 wrap_content 到 margin 支援

編輯:關於 Android 程式設計

引子:一個標準的自定義 ViewGroup 應該包含什麼

第一部分

  • 支援 wrap_content:當 ViewGroup 的寬高設為 wrap_content 時,其尺寸應根據子 View 的實際大小來決定。如果不特別處理,「wrap_content」的效果會等同於「match_parent」。
  • 支援 Padding。
  • 其子 View 支援 margin。
  • 支援自定義屬性,例如 gravity。

第二部分

支援滾動效果(當然,取決於你是否有滾動需求)。

第三部分

滑動事件衝突處理,也就是 touch 事件的分發。

接下來,我們一步步實現以上內容。

第一步:自己寫一個橫向的 LinearLayout(先實現支援 wrap_content 和 padding)

必須掌握的內容

onMeasure 的寫法、onLayout 的寫法。

難點

onMeasure 中 widthMeasureSpec、heightMeasureSpec 的理解。這裡不展開解釋,只需知道:正是因為 MeasureSpec 的規則,如果你不特別處理,就會導致 wrap_content 的效果變成 match_parent。換句話說,子 View 的尺寸並不完全由它自己決定,還與父容器傳遞過來的測量規格有關。

onLayout 中 l、t、r、b 的含義。這四個值是經過 onMeasure 測量後,得到的這個 MyViewGroup 的左上右下座標。要注意,l、t、r、b 已經計入了其父 ViewGroup 的 padding 值(當然也包括 MyViewGroup 自身的 padding)。這四個值建議印出來看看就明白了,否則很難寫好 onLayout。

具體來說:

  • l = 自定義 ViewGroup 的父 ViewGroup 的 leftPadding
  • t = 父 ViewGroup 的 topPadding
  • r = 父 ViewGroup 的 leftPadding + MyViewGroup 的寬度(即 desireWidth)
  • b = 父 ViewGroup 的 topPadding + MyViewGroup 的高度(即 desireHeight)

開始

大家都知道,自定義 View 要經過 onMeasure、onLayout、onDraw 三個流程。

onMeasure 裡要完成的內容

(再次強調,這裡說的是自定義 ViewGroup,自定義 View 不在本文討論範圍)

要測量內部所有子 View 的寬高

measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec)

measure(int widthMeasureSpec, int heightMeasureSpec)

這兩個方法意思相同,都可以用:第一個是測量每一個子 View,第二個則是讓每個子 View 去測量自己。

測量 ViewGroup 自己的寬高

如果你懶得支援 wrap_content,只需寫 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 即可,它會呼叫父類的流程去測量(源碼其實呼叫的是 setMeasuredDimension(int measuredWidth, int measuredHeight))。不支援 wrap_content 的意思就是:當你把寬高設為 wrap_content 時,實際效果卻是 match_parent。

若要支援 wrap_content,則使用下面的方法來測量 ViewGroup 自身的寬高:

setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec), resolveSize(desireHeight, heightMeasureSpec));

當 ViewGroup 寬度設為 wrap_content 時,它的寬度應該是所有子 View 寬度之和再加上左右 padding(先不考慮子 View 的 margin)。因此在測量每個子 View 時,要累加所有子 View 寬度再加上左右 padding 作為 ViewGroup 的寬度(若你明確設為 100dp,那就直接是 100dp)。由於本例是橫向排列,所以 ViewGroup 的高度就是最高的子 View 高度再加上上下 padding。

也就是:

  • desireWidth = 所有子 View 寬度累加之和 + 左右 padding
  • desireHeight = 最高子 View 的高度 + 上下 padding

onMeasure 模板程式碼(僅支援 wrap_content 和 padding,尚不支援 margin):

 ` @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // ★1. 計算所有child view 要占用的空間 desireWidth = 0;//累加所有子View的寬度,作為MyViewGroup寬度設為wrap_content時的寬度 desireHeight = 0;//本例子是橫向排列的ViewGroup,所以,MyViewGroup高度設為wrap_content時,其高度是其所有子View中最高子View的高度 int count = getChildCount(); for (int i = 0; i < count; ++i) { View v = getChildAt(i); //1.1 開始遍歷測量所有的子View,並且根據實際情況累加子View的寬(或者高),為了計算整個viewgroup的寬度(高度) if (v.getVisibility() != View.GONE) {//不去測量Gone的子View measureChild(v, widthMeasureSpec, heightMeasureSpec); --------------只需要根據你的需求,更改虛線內部的代碼即可,其余的不用改-------------- //由於橫向排列,累加所有的子View的寬度 desireWidth += v.getMeasuredWidth(); //高度是子View中最高的高度 desireHeight = Math .max(desireHeight, v.getMeasuredHeight()); --------------只需要根據你的需求,更改虛線內部的代碼即可,其余的不用改-------------- } } // 1.2 考慮padding值 //到目前為止desireWidth為所有子View的寬度的累加,作為MyViewGroup的總寬度,要加上左右padding值 desireWidth += getPaddingLeft() + getPaddingRight(); //高度同理略 desireHeight += getPaddingTop() + getPaddingBottom(); //★2.測量ViewGroup的寬高,如果不寫這一步,使用wrap_content時效果為match_parent的效果 // (下面的寫法比較簡潔,《Android群英傳》介紹了另外一種寫法,比這個稍微麻煩一點) // see if the size is big enough desireWidth = Math.max(desireWidth, getSuggestedMinimumWidth()); desireHeight = Math.max(desireHeight, getSuggestedMinimumHeight()); // super.onMeasure(widthMeasureSpec,heightMeasureSpec); setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec), resolveSize(desireHeight, heightMeasureSpec)); }` 

onLayout 要實現的內容

  ` @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { //這個自定義的ViewGroup的有效內容的四個邊界 final int parentLeft = getPaddingLeft();//這個MyViewGroup的最左邊的距離(純粹的內容的左邊界,不含padding) final int parentTop = getPaddingTop();//這個MyViewGroup的最上邊的距離(純粹的內容的上邊界,不含padding) final int parentRight = r - l - getPaddingRight();//這個MyViewGroup的最右邊的距離(純粹的內容的右邊界,不含padding) final int parentBottom = b - t - getPaddingBottom();//這個MyViewGroup的最下邊的距離(純粹的內容的下邊界,不含padding) if (BuildConfig.DEBUG) Log.d("onlayout", "parentleft: " + parentLeft + " parenttop: " + parentTop + " parentright: " + parentRight + " parentbottom: " + parentBottom+"\n"+ " l: " + l+ " t: " + t+ " r: " + r+ " b: " + b); int left = parentLeft; int top = parentTop; int count = getChildCount(); for (int i = 0; i < count; i++) { View v = getChildAt(i); if (v.getVisibility() != View.GONE) { //得到每一個子View的測量後的寬高 final int childWidth = v.getMeasuredWidth(); final int childHeight = v.getMeasuredHeight(); //開始布局每一個子View(左、上、右=左+子View寬、下=上+子View高) v.layout(left, top, left + childWidth, top + childHeight); //由於本例是橫向排列的,所以每一個子View的left值要遞增 left += childWidth; } } }` 

完整程式碼:

 ` public class MyViewGroup extends ViewGroup { private int desireWidth; private int desireHeight; public MyViewGroup(Context context) { this(context, null); } public MyViewGroup(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // ★1. 計算所有child view 要占用的空間 desireWidth = 0;//累加所有子View的寬度,作為MyViewGroup寬度設為wrap_content時的寬度 desireHeight = 0;//本例子是橫向排列的ViewGroup,所以,MyViewGroup高度設為wrap_content時,其高度是其所有子View中最高子View的高度 int count = getChildCount(); for (int i = 0; i < count; ++i) { View v = getChildAt(i); //1.1 開始遍歷測量所有的子View,並且根據實際情況累加子View的寬(或者高),為了計算整個viewgroup的寬度(高度) if (v.getVisibility() != View.GONE) {//不去測量Gone的子View measureChild(v, widthMeasureSpec, heightMeasureSpec); //由於橫向排列,累加所有的子View的寬度 desireWidth += v.getMeasuredWidth(); //高度是子View中最高的高度 desireHeight = Math .max(desireHeight, v.getMeasuredHeight()); } } // 1.2 考慮padding值 //到目前為止desireWidth為所有子View的寬度的累加,作為MyViewGroup的總寬度,要加上左右padding值 desireWidth += getPaddingLeft() + getPaddingRight(); //高度同理略 desireHeight += getPaddingTop() + getPaddingBottom(); //★2.測量ViewGroup的寬高,如果不寫這一步,使用wrap_content時效果為match_parent的效果 // (下面的寫法比較簡潔,《Android群英傳》介紹了另外一種寫法,比這個稍微麻煩一點) // see if the size is big enough desireWidth = Math.max(desireWidth, getSuggestedMinimumWidth()); desireHeight = Math.max(desireHeight, getSuggestedMinimumHeight()); //super.onMeasure(widthMeasureSpec,heightMeasureSpec); setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec), resolveSize(desireHeight, heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { //這個自定義的ViewGroup的有效內容的四個邊界 final int parentLeft = getPaddingLeft();//這個MyViewGroup的最左邊的距離(純粹的內容的左邊界,不含padding) final int parentTop = getPaddingTop();//這個MyViewGroup的最上邊的距離(純粹的內容的上邊界,不含padding) final int parentRight = r - l - getPaddingRight();//這個MyViewGroup的最右邊的距離(純粹的內容的右邊界,不含padding) final int parentBottom = b - t - getPaddingBottom();//這個MyViewGroup的最下邊的距離(純粹的內容的下邊界,不含padding) if (BuildConfig.DEBUG) Log.d("onlayout", "parentleft: " + parentLeft + " parenttop: " + parentTop + " parentright: " + parentRight + " parentbottom: " + parentBottom + "\n" + " l: " + l + " t: " + t + " r: " + r + " b: " + b); int left = parentLeft; int top = parentTop; int count = getChildCount(); for (int i = 0; i < count; i++) { View v = getChildAt(i); if (v.getVisibility() != View.GONE) { //得到每一個子View的測量後的寬高 final int childWidth = v.getMeasuredWidth(); final int childHeight = v.getMeasuredHeight(); //開始布局每一個子View(左、上、右=左+子View寬、下=上+子View高) v.layout(left, top, left + childWidth, top + childHeight); //由於本例是橫向排列的,所以每一個子View的left值要遞增 left += childWidth; } } } } 

`

總結

一般情況下,自定義 ViewGroup 支援 wrap_content 和 padding 就夠用了。

第二步:自己寫一個橫向的 LinearLayout(實現支援子 View 的 margin)

每一個自定義 ViewGroup 都必須自定義這個類別的 LayoutParams,以及後面那三個方法,否則會在型別轉換時拋出異常。其餘沒什麼特別要說的,計算距離時把 margin 考慮進去、佈局時也把 margin 算進來即可。

 `public class MyViewGroupMargin extends ViewGroup { private int desireWidth; private int desireHeight; public MyViewGroupMargin(Context context) { this(context, null); } public MyViewGroupMargin(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // ★1. 計算所有child view 要占用的空間 desireWidth = 0;//累加所有子View的寬度,作為MyViewGroup寬度設為wrap_content時的寬度 desireHeight = 0;//本例子是橫向排列的ViewGroup,所以,MyViewGroup高度設為wrap_content時,其高度是其所有子View中最高子View的高度 int count = getChildCount(); for (int i = 0; i < count; ++i) { View v = getChildAt(i); //1.1 開始遍歷測量所有的子View,並且根據實際情況累加子View的寬(或者高),為了計算整個viewgroup的寬度(高度) if (v.getVisibility() != View.GONE) {//不去測量Gone的子View LayoutParams lp = (LayoutParams) v.getLayoutParams(); //▲變化1:將measureChild改為measureChildWithMargin measureChildWithMargins(v, widthMeasureSpec, 0, heightMeasureSpec, 0); /*原來: measureChild(v, widthMeasureSpec, heightMeasureSpec);*/ //▲變化2:這裡在累加所有的子View的寬度時加上他自己的margin desireWidth += v.getMeasuredWidth() + lp.leftMargin + lp.rightMargin; desireHeight = Math .max(desireHeight, v.getMeasuredHeight() + lp.topMargin + lp.bottomMargin); /*原來://由於橫向排列,累加所有的子View的寬度 desireWidth += v.getMeasuredWidth(); //高度是子View中最高的高度 desireHeight = Math .max(desireHeight, v.getMeasuredHeight());*/ } } // 1.2 考慮padding值 //到目前為止desireWidth為所有子View的寬度的累加,作為MyViewGroup的總寬度,要加上左右padding值 desireWidth += getPaddingLeft() + getPaddingRight(); //高度同理略 desireHeight += getPaddingTop() + getPaddingBottom(); //★2.測量ViewGroup的寬高,如果不寫這一步,使用wrap_content時效果為match_parent的效果 // (下面的寫法比較簡潔,《Android群英傳》介紹了另外一種寫法,比這個稍微麻煩一點) // see if the size is big enough desireWidth = Math.max(desireWidth, getSuggestedMinimumWidth()); desireHeight = Math.max(desireHeight, getSuggestedMinimumHeight()); setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec), resolveSize(desireHeight, heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int parentLeft = getPaddingLeft(); final int parentRight = r - l - getPaddingRight(); final int parentTop = getPaddingTop(); final int parentBottom = b - t - getPaddingBottom(); if (BuildConfig.DEBUG) Log.d("onlayout", "parentleft: " + parentLeft + " parenttop: " + parentTop + " parentright: " + parentRight + " parentbottom: " + parentBottom); int left = parentLeft; int top = parentTop; int count = getChildCount(); for (int i = 0; i < count; ++i) { View v = getChildAt(i); if (v.getVisibility() != View.GONE) { LayoutParams lp = (LayoutParams) v.getLayoutParams(); final int childWidth = v.getMeasuredWidth(); final int childHeight = v.getMeasuredHeight(); //▲變化1:左側要加上這個子View的左側margin left += lp.leftMargin; //▲變化2:上側要加上子View的margin top = parentTop + lp.topMargin; if (BuildConfig.DEBUG) { Log.d("onlayout", "child[width: " + childWidth + ", height: " + childHeight + "]"); Log.d("onlayout", "child[left: " + left + ", top: " + top + ", right: " + (left + childWidth) + ", bottom: " + (top + childHeight)); } v.layout(left, top, left + childWidth, top + childHeight); //▲變化3:因為是橫向排列的,所以下一個View的左側加上這個view的右側的margin(如果是縱向排列的則對應改變top) left += childWidth + lp.rightMargin; } } } //★★★★★★★★★★★★★★★★★★★★★★★要使用margin必須寫下面的方法★★★★★★★★★★★★★★★★★★★★★ //***開始***每一個自定義ViewGroup都必須,自定義這個類LayoutParams,以及後面的三個方法,否則強轉報異常,模板代碼照抄即可************** 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 source) { super(source); } public LayoutParams(MarginLayoutParams source) { super(source); } } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } @Override public ViewGroup.LayoutParams generateLayoutParams( AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected ViewGroup.LayoutParams generateLayoutParams( ViewGroup.LayoutParams p) { return new LayoutParams(p); } //***結束***每一個自定義ViewGroup都必須,自定義這個類LayoutParams,以及後面的三個方法,否則強轉報異常,模板代碼照抄即可************** } 

`

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved