編輯:關於 Android 程式設計
在 Android 裡自定義 View,本質上不複雜:繼承合適的父類,重載需要的方法。即便如此,實際編碼時還是容易踩坑。本文總結兩個我親身遇到過的問題,希望能幫你少走彎路。
當我們需要繼承一個布局比較複雜的 ViewGroup(最常見的是 LinearLayout 和 RelativeLayout)時,通常會寫一個 XML 布局文件,然後在自定義 View 的構造函數中 inflate 它。
先新建 MyLayout 類:
/**
* 自定義 LinearLayout
*/
public class MyLayout extends LinearLayout {
public MyLayout(Context context) {
super(context);
init();
}
private void init() {
setOrientation(VERTICAL);
View rootView = inflate(getContext(), R.layout.my_layout, this);
((TextView) rootView.findViewById(R.id.title)).setText("MyLayout");
((TextView) rootView.findViewById(R.id.desc)).setText("A customized layout");
}
}然後新建 my_layout.xml,把根節點設為 merge:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="https://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/title"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</merge>用 Android SDK 自帶的 Layout Inspector(舊版本叫 Monitor)工具查看運行時的視圖層級:

最頂層是 MyLayout(在工具中顯示為 FrameLayout 的計量包裝),下面直接兩個 TextView,層級乾淨,沒有冗餘。
但如果不小心把根節點寫成了 LinearLayout 呢?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/title"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
層級立刻多了一層:MyLayout 裡面套了一個毫無作用的 LinearLayout,裡面才是兩個 TextView。這個多餘的 ViewGroup 會參與 measure、layout、draw 三個流程,直接影響性能。
merge 的作用就是「把子節點直接添加到指定父容器,而不生成中間節點」。配合 inflate(xml, this, true) 的第三個參數 attachToRoot=true,子 View 會被直接掛到自定義 ViewGroup 上。
需要注意 merge 的使用前提:它只能配合帶 root 的 inflate 使用。單獨用 inflate(R.layout.xxx, null) 會直接拋 InflateException,因為 merge 沒有自己可以返回的根 View。
這個坑讓我折騰了很久。當時我這樣自定義了一個 Button:
public class MyButton extends Button {
public MyButton(Context context) {
this(context, null);
}
public MyButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
}乍看毫無問題:構造函數鏈正確收斂到三參數版本,init() 也會被調用。但無論我怎麼修改 MyButton 的屬性,顯示效果就是就是不對。
問題出在哪?在於 Button 類自己在構造函數中使用了一個 defStyleAttr,而我這種「自我收斂」的寫法把它丟掉了。看源碼就清楚了:
@RemoteView
public class Button extends TextView {
public Button(Context context) {
this(context, null);
}
public Button(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.buttonStyle);
}
public Button(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public Button(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
}看到關鍵了嗎?Button 的兩參數構造函數硬編碼傳入了 com.android.internal.R.attr.buttonStyle,這是系統 Button 的默認樣式引用。
而當我用 this(context, null) 時,走的是 Button 的三參數構造函數,defStyleAttr 被強制設為 0。結果就是:系統默認樣式完全丟失,Button 變成一個沒有背景、沒有 padding、沒有正確字號的裸 TextView。
而 XML 中 inflate 出來的 View,走的恰好是兩參數構造函數——這條路徑上 defStyleAttr 被正確傳遞了。這也解釋了為什麼這個 bug 表現得很「靈異」:代碼邏輯看起來對,效果卻怎麼都不對。
後來我的習慣變成:寫自定義 View 前先看父類源碼。如果不確定,就老老實實地直接調父類對應的構造函數,不要自己做收斂:
public class MyButton extends Button {
public MyButton(Context context) {
super(context);
init();
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
}這樣寫的好處是:每個構造函數都把參數原封不動交給父類,父類内部的樣式邏輯不會被破壞。代碼多幾行,但行為可預期。
1. 別忘了添加 AttributeSet 構造函數。只寫 MyView(Context) 一個構造函數,在 XML 中使用時會直接崩潰,因為 LayoutInflater 找不到匹配的構造函數。四個標準構造函數(Context / Context+AttributeSet / +int defStyleAttr / +int defStyleRes)中,前兩個是必須的。
2. 自定義屬性記得加命名空間。在 res/values/attrs.xml 中定義 declare-styleable,然後在代碼中用 context.obtainStyledAttributes(attrs, R.styleable.MyView) 讀取,最後務必調用 recycle()。
3. onMeasure 中調 super 要慎重。如果直接 super.onMeasure(),高度會由系統按 wrap_content 給定;若需要自定義測量邏輯,必須自己處理 MeasureSpec 的三種模式(UNSPECIFIED / AT_MOST / EXACTLY)。
4. 避免在 onDraw 中 new 對象。Paint、Path、RectF 都應該在構造函數中創建並複用。onDraw 可能一幀調用多次,在其中創建對象會加劇 GC 壓力,導致掉幀。
5. Button 的高度問題。Button 的默認高度受 buttonStyle 中的 minHeight/padding 影響,設 layout_height="wrap_content" 時高度往往不如預期。要精確控制,用 AppCompatButton 並顯式覆蓋 android:minHeight 與 android:insetTop。
自定義 View 的坑大多不是「不會寫」,而是「寫了但與框架的預期不一致」。養成看源碼的習慣,能省下大量排查時間。
Android 自定義 View:實作字母導航欄
在聯絡人、音樂或相簿等應用中,字母導航欄是很常見的輔助操作。本文將說明如何透過自定義 View,實作一個可滑動、可高亮、可與 ListView 聯動的字母索引欄。 自定
Android記事本App完整源碼解析:密碼登入與SQLite資料儲存實作
這個應用實作了密碼登入功能,記事本內容支援新增、刪除、修改、查詢等各項操作,並以 ListView 顯示每次保存的記事內容,完整實現記事本的基本功能。程式碼皆附有詳細註解
Android 觸摸事件分發機制全解析:源碼、四種情況與點擊事件來源
Android 中的事件分為按鍵事件與觸摸事件,本文聚焦觸摸事件。一次完整的觸摸會由一個 ACTION_DOWN、若干個 ACTION_MOVE 和一個 ACTION_U
Android UI 組件 AppWidget 控件入門詳解
AppWidget(應用小部件)是我們可以放到桌面、方便隨時操作的小組件。本文從原理到實踐,帶大家完整入門 AppWidget 的開發。 一、Widget 引入 我們可以