Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

徹底搞懂 Android 的 LayoutInflater.inflate() 與 attachToRoot

編輯:Android 資訊

我們寫 Android 時,經常會複製貼上一些看起來理所當然的樣板代碼,久了反而忽略了背後那些設計得相當精巧的細節。LayoutInflater 就是這樣一個例子,特別是它在 Fragment 的 onCreateView() 裡填充 View 的方式,值得我們停下來好好想一想。這個類的核心職責很單純:把 XML 佈局文件翻譯成對應的 ViewGroup 與各類 Widget 控件。

我曾翻遍官方文檔和網路上的討論,想弄清楚 inflate() 方法的種種細節,結果卻發現不少人不僅對它一知半解,甚至根本就是用錯了。這份困惑很大程度上源自 Google 對 attachToRoot(也就是 inflate() 的第三個參數)那段語焉模糊的說明:

被填充的層是否應該附在 root 參數內部?如果是 false,root 參數只是用於為 XML 根元素 View 創建正確的 LayoutParams 子類。

翻成白話就是這樣:當 attachToRoot 為 true,第一個參數指定的佈局會被填充,並直接掛到第二個參數指定的 ViewGroup 底下,方法返回的是這個合併後的 View,其根節點就是那個 ViewGroup。而當它為 false,第一個參數的佈局同樣會被填充,但會作為一個獨立 View 返回,根節點就是佈局文件本身的根元素。無論 true 還是 false,都需要正確的 LayoutParams,才能對產生的 View 進行準確的測量與定位。

換句話說,attachToRoot 傳 true 意味著「填充完就順手加進 ViewGroup」;傳 false 則意味著「先造好,之後再由我決定怎麼放進去」。

接下來我們分兩種情況各舉幾個例子,把這件事徹底說清楚。

當 attachToRoot 為 True

假設佈局文件裡寫了一顆 Button,寬高分別設為 match_parent。

<Button xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/custom_button"> </Button>

現在我們想在建構上把這顆按鈕動態加進某個 Fragment 或 Activity 的 LinearLayout。若這個 LinearLayout 已經是成員變數 mLinearLayout,只要一行就能搞定:

inflater.inflate(R.layout.custom_button, mLinearLayout, true);

我們指定了要填充的佈局資源,再告訴 LayoutInflater 把它加到 mLinearLayout 裡。此時 Button 的 LayoutParams 類型會是 LinearLayout.LayoutParams。

下面這行寫法效果完全相同,因為兩參數版本的 inflate() 會自動把 attachToRoot 設為 true。

inflater.inflate(R.layout.custom_button, mLinearLayout);

另一種適合傳 true 的場景,是實作自定義 View。我們看一個佈局根節點帶有標籤的例子。這個標籤的作用,是讓佈局的根 ViewGroup 可以有多種類型。

public class MyCustomView extends LinearLayout { ... private void init() { LayoutInflater inflater = LayoutInflater.from(getContext()); inflater.inflate(R.layout.view_with_merge_tag, this); } }

這是 attachToRoot 相當漂亮的用法。由於這個佈局沒有自己的根 ViewGroup,我們就把自定義的 LinearLayout 當作根節點傳進去。如果換成一個以 FrameLayout 為根的佈局,那麼 FrameLayout 連同它的子元素都會被填充,最後一起掛到作為根的 LinearLayout 裡,形成 LinearLayout 包住 FrameLayout 及其子元素的結構。

當 attachToRoot 為 False

那什麼時候該傳 false 呢?這種情況下,第一個參數指定的 View 不會被自動加進第二個參數的 ViewGroup。

還是那顆 Button,我們想透過佈局把它加進 mLinearLayout。attachToRoot 為 false 時依然能做到,只是得自己動手:

Button button = (Button) inflater.inflate(R.layout.custom_button, mLinearLayout, false); mLinearLayout.addView(button);

這兩行,等價於前面 attachToRoot 為 true 時的那一行。傳 false 的意思是「先別急著把 View 加進根容器,我等等自己處理」,而所謂的「等等」,就是在 inflate() 之後再呼叫 addView()。

就這個例子而言,傳 false 反而讓代碼變多、變麻煩,直接用一行把 attachToRoot 設成 true 顯然更乾脆。那麼,什麼情況下 attachToRoot 是非 false 不可的呢?

每一個 RecyclerView 的子項,都必須在 attachToRoot 為 false 的前提下填充,通常是在 onCreateViewHolder() 裡完成。

public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(getActivity()); View view = inflater.inflate(android.R.layout.list_item_recyclerView, parent, false); return new ViewHolder(view); }

因為決定何時展示子 View 的是 RecyclerView,而不是我們自己。凡是「不由我們負責把 View 加進 ViewGroup」的場合,attachToRoot 都應該設為 false。

同樣地,在 Fragment 的 onCreateView() 裡填充並返回 View 時,也要傳 false。若傳 true 就會拋出 IllegalStateException,因為那個子 View 已經有父容器了。Fragment 的 View 該擺到 Activity 的哪個位置,是由 FragmentManager 透過 add、remove、replace 等操作來決定的。

FragmentManager fragmentManager = getSupportFragmentManager(); Fragment fragment = fragmentManager.findFragmentById(R.id.root_viewGroup); if (fragment == null) { fragment = new MainFragment(); fragmentManager.beginTransaction().add(R.id.root_viewGroup, fragment).commit(); }

上面這段裡的 root_viewGroup,就是 Activity 中用來承載 Fragment 的容器,它會作為第二個參數傳進 onCreateView(),也正是你在 inflate() 裡傳入的那個 ViewGroup。FragmentManager 會負責把 Fragment 的 View 加進去,你自然不希望它被加兩次。

public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_layout, parentViewGroup, false); … return view; }

於是有人會問:既然 onCreateView() 裡不需要真的把 View 加進容器,那為什麼還要傳這個 ViewGroup 進來?答案是——即便當下不馬上加,我們仍然需要這個父容器的 LayoutParams,好在未來真正添加時決定 View 的尺寸與位置。

網路上你一定會碰到一些不靠譜的建議,比如叫你乾脆把根 ViewGroup 傳成 null。但只要父容器是拿得到的,就應該老老實實傳進去。

Lint 會對「傳 null 當 root」發出警告。你的 App 未必會閃退,但行為可能變得古怪。當子 View 拿不到正確的 LayoutParams 時,系統會改用 generateDefaultLayoutParams() 自己算一套。

而這套預設值往往不是你想要的,你在 XML 裡指定的 LayoutParams 會被直接忽略。明明設了子 View 要填滿父寬度,卻因為父 View 是 wrap_content,最終顯示出來的 View 就小了一大圈。

確實有一種情況可以傳 null 當 root:為 AlertDialog 建立自定義 View 時,此刻還拿不到父容器。

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext); View customView = inflater.inflate(R.layout.custom_alert_dialog, null); ... dialogBuilder.setView(customView); dialogBuilder.show();

這種情況下傳 null 是可以接受的。只不過我後來發現,AlertDialog 終究還是會重寫 LayoutParams,把各項都設成 match_parent。但原則不變:只要有 ViewGroup 能傳,就傳它。

避開崩潰、異常與誤解

希望這篇文章能幫你在使用 LayoutInflater 時少踩坑。最後把重點整理成幾條:

  • 只要拿得到 ViewGroup 當根節點,就傳它。
  • 盡量別把 null 當作根 ViewGroup 傳入。
  • 當「不由你負責把佈局 View 加進容器」時,把 attachToRoot 設為 false。
  • 不要在某個 View 已經被加進容器時再傳 true。
  • 實作自定義 View,往往很適合把 attachToRoot 設為 true。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved