編輯:關於 Android 程式設計
前面我們已經看過幾種自定義控件的做法:音頻條,以及可複用的組合控件。還沒看過的建議先補上,因為本篇會直接沿用其中的成果。
今天要往下一層走:自己寫一個 ViewGroup。
1. 什麼是 ViewGroup?
ViewGroup 是一種容器,可以包含零個或多個 View 與子 ViewGroup。

2. ViewGroup 有什麼作用?
它負責存放與管理子控件,並依自己的測量模式去測量子 View、決定子 View 的位置。這兩件事分別對應兩個方法:onMeasure() 管大小,onLayout() 管位置。接下來就從這兩個方法著手。
一如往常,先繼承並把三個建構子補齊:
public class CustomViewGroup extends ViewGroup {
public CustomViewGroup(Context context) {
this(context, null);
}
public CustomViewGroup(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
measureChild(children, widthMeasureSpec, heightMeasureSpec);
}
}
寫法很直白:先取得子 View 數量,逐一取出,再呼叫 measureChild() 測量。注意這裡把父容器自己的 widthMeasureSpec、heightMeasureSpec 一起傳進去了——因為子 View 的測量結果,本來就取決於父容器提供的測量模式。
protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
final LayoutParams lp = child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(
parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight,
lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(
parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom,
lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
它先取得子 View 的 LayoutParams,再把「父容器的測量規格 + 自己的 padding + 子 View 的寬高參數」一起交給 getChildMeasureSpec() 換算出子 View 的測量規格。由此可得第一個結論:子 View 的大小 = 父容器的測量模式 + 子 View 的 LayoutParams + 父容器的 padding。
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) {
// 父容器給了精確尺寸
case MeasureSpec.EXACTLY:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// 父容器給了最大尺寸
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// 父容器不限大小,讓子 View 自己決定
case MeasureSpec.UNSPECIFIED:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
邏輯是兩層判斷:先扣掉 padding 得到可用大小 size,再依父容器的 specMode(EXACTLY / AT_MOST / UNSPECIFIED)分別判斷子 View 的 childDimension(明確數值 / MATCH_PARENT / WRAP_CONTENT),最後組回一組新的 MeasureSpec。知道了子 View 的測量模式與大小,它該有多大就確定了。
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
int preHeight = 0;
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
int cHeight = children.getMeasuredHeight();
if (children.getVisibility() != View.GONE) {
children.layout(l, preHeight, r, preHeight += cHeight);
}
}
}
先取得子 View 數量並逐一走訪,然後用一個變數 preHeight 記錄「到目前為止累積的高度」,每個子 View 就從這個高度開始往下排。這樣就達到了垂直依次排列的效果。
值得注意的是,View 的 layout() 本身並沒有硬性規定怎麼排:
public void layout(int l, int t, int r, int b) {
if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
int oldL = mLeft;
int oldT = mTop;
int oldB = mBottom;
int oldR = mRight;
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);
mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnLayoutChangeListeners != null) {
ArrayList<OnLayoutChangeListener> listenersCopy =
(ArrayList<OnLayoutChangeListener>) li.mOnLayoutChangeListeners.clone();
int numListeners = listenersCopy.size();
for (int i = 0; i < numListeners; ++i) {
listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
}
}
}
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}
關鍵是 setFrame(l, t, r, b)(決定四個邊界座標),而真正的定位邏輯被交給 onLayout(changed, l, t, r, b)。而 ViewGroup 裡的這個方法:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
是空的。換句話說,系統把最大的自由度留給了我們——排法完全自訂。
拿前面寫過的自定義 View 當子 View 來試試。
custom_viewgroup.xml:
<?xml version="1.0" encoding="utf-8"?>
<com.sanhuimusic.mycustomview.view.CustomViewGroup
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:custom="https://schemas.android.com/apk/res-auto"
android:id="@+id/customViewGroup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#999999">
<com.sanhuimusic.mycustomview.view.CompositeViews
android:id="@+id/topBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#999999"
custom:titleText="@string/titleText"
custom:titleColor="#000000"
custom:titleTextSize="@dimen/titleTextSize"
custom:titleBackground="#999999"
custom:leftText="@string/leftText"
custom:leftTextColor="#FFFFFF"
custom:leftBackground="#666666"
custom:leftTextSize="@dimen/leftTextSize"
custom:rightText="@string/rightText"
custom:rightTextColor="#FFFFFF"
custom:rightBackground="#666666"
custom:rightTextSize="@dimen/rightTextSize" />
<com.sanhuimusic.mycustomview.view.AudioBar
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.sanhuimusic.mycustomview.view.CustomViewGroup>
MainActivity:
public class MainActivity extends AppCompatActivity {
private CompositeViews topBar;
private Context mContext;
private CustomViewGroup mViewGroupContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_viewgroup);
mContext = this;
init();
}
private void init() {
mViewGroupContainer = (CustomViewGroup) findViewById(R.id.customViewGroup);
topBar = (CompositeViews) findViewById(R.id.topBar);
topBar.setOnTopBarClickListener(new CompositeViews.TopBarClickListener() {
@Override
public void leftClickListener() {
ToastUtil.makeText(MainActivity.this, "您點擊了返回鍵", Toast.LENGTH_SHORT).show();
}
@Override
public void rightClickListener() {
ToastUtil.makeText(MainActivity.this, "您點擊了搜尋鍵", Toast.LENGTH_SHORT).show();
}
});
}
}

子 View 確實垂直排列下來了。但馬上會想到一個問題:前面在寫自定義 View 時提過,wrap_content 需要特別處理才能正確生效——自定義 ViewGroup 也是同樣的道理。試著把 CustomViewGroup 的寬高改成 wrap_content,果然不支援。
所以自定義 ViewGroup 有兩件事一定要處理:
wrap_content 情境下的測量。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
measureChild(children, widthMeasureSpec, heightMeasureSpec);
}
/** 讓它支援自身的 wrap_content */
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
int mWidth = 0;
int mHeight = 0;
int mMaxWidth = 0;
if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
// 寬高都是 wrap_content:累加子 View 的寬高
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
mWidth += children.getMeasuredWidth();
mHeight += children.getMeasuredHeight();
}
setMeasuredDimension(mWidth, mHeight);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
// 只有寬是 wrap_content:取子 View 最大寬
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
mMaxWidth = Math.max(mMaxWidth, children.getMeasuredWidth());
}
setMeasuredDimension(mMaxWidth, heightSpecSize);
} else if (heightSpecMode == MeasureSpec.AT_MOST) {
// 只有高是 wrap_content:累加子 View 高度
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
mHeight += children.getMeasuredHeight();
}
setMeasuredDimension(widthSpecSize, mHeight);
}
}
核心觀念:自定義 ViewGroup 若不呼叫 setMeasuredDimension(),系統會回傳一個未初始化的尺寸,畫面就全亂了。這裡分三種情況處理:

先取出四邊 padding:
leftPadding = getPaddingLeft(); topPadding = getPaddingTop(); rightPadding = getPaddingRight(); bottomPadding = getPaddingBottom();
在計算尺寸時把它們加回去:
if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
mWidth += children.getMeasuredWidth();
mHeight += children.getMeasuredHeight();
}
setMeasuredDimension(mWidth + leftPadding + rightPadding,
mHeight + topPadding + bottomPadding);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
mMaxWidth = Math.max(mMaxWidth, children.getMeasuredWidth());
}
setMeasuredDimension(mMaxWidth + leftPadding + rightPadding,
heightSpecSize + topPadding + bottomPadding);
} else if (heightSpecMode == MeasureSpec.AT_MOST) {
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
mHeight += children.getMeasuredHeight();
}
setMeasuredDimension(widthSpecSize + leftPadding + rightPadding,
mHeight + topPadding + bottomPadding);
}
定位時同樣要納入 padding:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
int preHeight = topPadding; // 不再從 0 開始
for (int i = 0; i < childCount; i++) {
View children = getChildAt(i);
int cHeight = children.getMeasuredHeight();
if (children.getVisibility() != View.GONE) {
children.layout(l + leftPadding,
preHeight,
r + rightPadding,
preHeight += cHeight);
}
}
}

除了上述兩點,實務上通常還會處理:
generateLayoutParams() 並讀取 MarginLayoutParams。layout_width="match_parent" 等屬性可能拿不到正確的 LayoutParams。自定義 ViewGroup 明顯比自定義 View 複雜,因為你要同時對「測量」與「排版」兩套流程負責。但拆解下來其實就是固定套路:onMeasure 決定自己多大、順便量好每個孩子;onLayout 決定每個孩子擺在哪。把這兩句話吃透,剩下的排列邏輯都只是這兩步的變形。
另外別忘了,本篇只處理了 UI 顯示,功能與事件(例如攔截滑動手勢)是另一個主題,可以後續再補。
解決難題:防止 App 在後台被殺後點擊桌面圖標重新啟動
項目中曾遇到一個百思不得其解的問題:在 app 使用過程中按了 home 鍵,然後去看看微信之類的其他應用,這時再點擊 app 的桌面圖標,app 卻是重新啟動的,而不是
Android N 對 Doze 打盹模式的強化:兩級限制該怎麼適配
為了延長電池續航、壓低記憶體佔用並提升整體效能,Android N 對系統行為做了一系列調整。這些調整會直接影響系統資源與通知對應用的可用性,因此每一項都值得逐條檢查,評
Android NDK 開發入門:從 JNI 概念到第一個 so 庫
一、JNI 是什麼 JNI 是 Java Native Interface 的縮寫,它定義了一套讓 Java 程式碼與原生程式碼(以 C/C++ 撰寫)互相溝通的方式。在
如何將 Android 專案打包成第三方 JAR 供他人使用
做專案時經常會遇到需要使用第三方 SDK 的情況。通常我們先把第三方 jar 包導入,再導入相應的資源檔,最後在自己的專案中呼叫。很多人只會用,卻不知道怎麼把自己的專案也