自定義 TitleBarView extends LinearLayout,建構子中 LayoutInflater.inflate(R.layout.title_bar, this),而 title_bar.xml 根標籤也是 <LinearLayout>,導致 兩層 LinearLayout 嵌套。
將佈局 XML 根標籤改為 <merge>,告訴 Inflater「直接把子 View 加入父容器,不建立額外 ViewGroup」。
<!-- 修正前:title_bar.xml -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView ... />
<ImageView ... />
</LinearLayout>
<!-- 修正後:title_bar.xml -->
<merge xmlns:android="https://schemas.android.com/apk/res/android">
<TextView ... />
<ImageView ... />
</merge>
// Java/Kotlin 建構子 (無需更動)
public TitleBarView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title_bar, this, true);
// true 表示 attachToRoot,子 View 直接加入 this (TitleBarView)
}
inflate(layout, parent, true) (attachToRoot=true) 使用。layout_width 等)會被忽略,由父容器決定。| 手段 | 適用場景 | 效果 |
|---|---|---|
ViewStub | 低頻顯示的複雜子佈局 (如錯誤頁、空狀態) | 延遲 inflate,啟動加速 |
include + merge | 跨佈局重用通用結構 | 減少重複 XML,結構扁平化 |
| ConstraintLayout | 複雜相對定位 | 單層扁平化,取代多層嵌套 |
| 自定義 View 直接 onDraw | 極簡 UI (如進度條、圖表) | 零 View 嵌套,效能最高 |
HierarchyViewer (舊) / ViewServer:離線分析 View 樹深度。<merge>。ConstraintLayout 扁平化。ViewStub 延遲載入。