2016/07/13

android 中的 Layoutinflator.inflate 的 attachToRoot?

Android 裡的 Layoutinflater 可以用來把 XML 轉換成 ViewGroup

通常拿來用在 Fragment 的 onCreateView() 方法裡
一般來說都是使用下面這個 inflate 方法


inflate
(int resource, ViewGroup root, boolean attachToRoot)
Inflate a new view hierarchy from the specified xml resource.

現在分析兩種情況,

attachToRoot 設為 true 的時候,代表 View 時直接被 attach 到 root group 裡,而且會回傳 root view

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


attachToRoot 設為 false 的時候代表 這個 inflate 出來的 View  不是馬上被 attach 到 ViewGroup,而是指說在未來的某一個時間點才會,這方法會回傳自己的 view。

例如先將 XML inflate 後,到某個時間點在自己加進 layout
Button button = (Button) inflater.inflate(R.layout.custom_button, mLinearLayout, false);
mLinearLayout.addView(button);

最常見的例子就是 ListView (RecyclerView),因為是由 RecyclerView 來控制什麼時間點才要將 View 加入

探討 View.inflate

另外如果我們是直接使用 View.inflate ,他的本質其實就是直接將 inflate 出來的加到 layout 裡
例如下面這樣其實等同於 Layoutinflator.inflate 並且帶 attachRoot = true
LinearLayout layout = (LinearLayout)findViewById(R.id.container);
View view = View.inflate(this, R.layout.layout_menu_item, layout);
後記:如果你的 XML root 是 就只能 attachToRoot = true 否則會出現 InflateException

Caused by: android.view.InflateException: can be used only with a valid ViewGroup root and attachToRoot=true

參考:https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

No comments:

Post a Comment