首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 自定義 View 優化:使用 標籤消除多餘 LinearLayout 嵌套

     編輯:程式設計綜合問答

問題場景

自定義 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) 使用。
  • 無法單獨預覽(AS Layout Inspector 會顯示錯誤),僅在 inflate 時生效。
  • 根標籤屬性(layout_width 等)會被忽略,由父容器決定。

其他優化手段

手段適用場景效果
ViewStub低頻顯示的複雜子佈局 (如錯誤頁、空狀態)延遲 inflate,啟動加速
include + merge跨佈局重用通用結構減少重複 XML,結構扁平化
ConstraintLayout複雜相對定位單層扁平化,取代多層嵌套
自定義 View 直接 onDraw極簡 UI (如進度條、圖表)零 View 嵌套,效能最高

檢測工具

  • Layout Inspector (AS):即時查看 View 階層、屬性。
  • Profile GPU Rendering:開發者選項 → GPU 呈現模式分析,找出過度繪製/深層嵌套。
  • HierarchyViewer (舊) / ViewServer:離線分析 View 樹深度。

最佳實踐總結

  1. 自定義 ViewGroup 根佈局用 <merge>。
  2. 複雜佈局改用 ConstraintLayout 扁平化。
  3. 低頻 UI 用 ViewStub 延遲載入。
  4. 定期用 Layout Inspector 檢視階層,目標 深度 < 10 層。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved