Android中LayoutInflater類的inflate方法的使用及注意事項

轉自:http://www.ithao123.cn/content-10951307.html

 

我們在講一個定義好的佈局文件(xml)文件加載到界面上展現出來的時候,通常會用到LayoutInflater的inflate方法,細心的同學會發現這個方法有四種重載,分別是:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root);

 

public View inflate(XmlPullParser parser, @Nullable ViewGroup root);
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot);
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot);

下面是Android Studio下查看到的源碼即相關方法的參數說明:


 
  1. /**

  2. * Inflate a new view hierarchy from the specified xml resource. Throws

  3. * {@link InflateException} if there is an error.

  4. *

  5. * @param resource ID for an XML layout resource to load (e.g.,

  6. * <code>R.layout.main_page</code>)

  7. * @param root Optional view to be the parent of the generated hierarchy.

  8. * @return The root View of the inflated hierarchy. If root was supplied,

  9. * this is the root View; otherwise it is the root of the inflated

  10. * XML file.

  11. */

  12. public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {

  13. return inflate(resource, root, root != null);

  14. }

  15.  
  16. /**

  17. * Inflate a new view hierarchy from the specified xml node. Throws

  18. * {@link InflateException} if there is an error. *

  19. * <p>

  20. * <em><strong>Important</strong></em>   For performance

  21. * reasons, view inflation relies heavily on pre-processing of XML files

  22. * that is done at build time. Therefore, it is not currently possible to

  23. * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.

  24. *

  25. * @param parser XML dom node containing the description of the view

  26. * hierarchy.

  27. * @param root Optional view to be the parent of the generated hierarchy.

  28. * @return The root View of the inflated hierarchy. If root was supplied,

  29. * this is the root View; otherwise it is the root of the inflated

  30. * XML file.

  31. */

  32. public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {

  33. return inflate(parser, root, root != null);

  34. }

  35.  
  36. /**

  37. * Inflate a new view hierarchy from the specified xml resource. Throws

  38. * {@link InflateException} if there is an error.

  39. *

  40. * @param resource ID for an XML layout resource to load (e.g.,

  41. * <code>R.layout.main_page</code>)

  42. * @param root Optional view to be the parent of the generated hierarchy (if

  43. * <em>attachToRoot</em> is true), or else simply an object that

  44. * provides a set of LayoutParams values for root of the returned

  45. * hierarchy (if <em>attachToRoot</em> is false.)

  46. * @param attachToRoot Whether the inflated hierarchy should be attached to

  47. * the root parameter? If false, root is only used to create the

  48. * correct subclass of LayoutParams for the root view in the XML.

  49. * @return The root View of the inflated hierarchy. If root was supplied and

  50. * attachToRoot is true, this is root; otherwise it is the root of

  51. * the inflated XML file.

  52. */

  53. public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {

  54. final Resources res = getContext().getResources();

  55. if (DEBUG) {

  56. Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("

  57. + Integer.toHexString(resource) + ")");

  58. }

  59.  
  60. final XmlResourceParser parser = res.getLayout(resource);

  61. try {

  62. return inflate(parser, root, attachToRoot);

  63. } finally {

  64. parser.close();

  65. }

  66. }

  67.  
  68. /**

  69. * Inflate a new view hierarchy from the specified XML node. Throws

  70. * {@link InflateException} if there is an error.

  71. * <p>

  72. * <em><strong>Important</strong></em>   For performance

  73. * reasons, view inflation relies heavily on pre-processing of XML files

  74. * that is done at build time. Therefore, it is not currently possible to

  75. * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.

  76. *

  77. * @param parser XML dom node containing the description of the view

  78. * hierarchy.

  79. * @param root Optional view to be the parent of the generated hierarchy (if

  80. * <em>attachToRoot</em> is true), or else simply an object that

  81. * provides a set of LayoutParams values for root of the returned

  82. * hierarchy (if <em>attachToRoot</em> is false.)

  83. * @param attachToRoot Whether the inflated hierarchy should be attached to

  84. * the root parameter? If false, root is only used to create the

  85. * correct subclass of LayoutParams for the root view in the XML.

  86. * @return The root View of the inflated hierarchy. If root was supplied and

  87. * attachToRoot is true, this is root; otherwise it is the root of

  88. * the inflated XML file.

  89. */

  90. public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {

  91. synchronized (mConstructorArgs) {

  92. Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

  93.  
  94. final Context inflaterContext = mContext;

  95. final AttributeSet attrs = Xml.asAttributeSet(parser);

  96. Context lastContext = (Context) mConstructorArgs[0];

  97. mConstructorArgs[0] = inflaterContext;

  98. View result = root;

  99.  
  100. try {

  101. // Look for the root node.

  102. int type;

  103. while ((type = parser.next()) != XmlPullParser.START_TAG &&

  104. type != XmlPullParser.END_DOCUMENT) {

  105. // Empty

  106. }

  107.  
  108. if (type != XmlPullParser.START_TAG) {

  109. throw new InflateException(parser.getPositionDescription()

  110. + ": No start tag found!");

  111. }

  112.  
  113. final String name = parser.getName();

  114.  
  115. if (DEBUG) {

  116. System.out.println("**************************");

  117. System.out.println("Creating root view: "

  118. + name);

  119. System.out.println("**************************");

  120. }

  121.  
  122. if (TAG_MERGE.equals(name)) {

  123. if (root == null || !attachToRoot) {

  124. throw new InflateException("<merge /> can be used only with a valid "

  125. + "ViewGroup root and attachToRoot=true");

  126. }

  127.  
  128. rInflate(parser, root, inflaterContext, attrs, false);

  129. } else {

  130. // Temp is the root view that was found in the xml

  131. final View temp = createViewFromTag(root, name, inflaterContext, attrs);

  132.  
  133. ViewGroup.LayoutParams params = null;

  134.  
  135. if (root != null) {

  136. if (DEBUG) {

  137. System.out.println("Creating params from root: " +

  138. root);

  139. }

  140. // Create layout params that match root, if supplied

  141. params = root.generateLayoutParams(attrs);

  142. if (!attachToRoot) {

  143. // Set the layout params for temp if we are not

  144. // attaching. (If we are, we use addView, below)

  145. temp.setLayoutParams(params);

  146. }

  147. }

  148.  
  149. if (DEBUG) {

  150. System.out.println("-----> start inflating children");

  151. }

  152.  
  153. // Inflate all children under temp against its context.

  154. rInflateChildren(parser, temp, attrs, true);

  155.  
  156. if (DEBUG) {

  157. System.out.println("-----> done inflating children");

  158. }

  159.  
  160. // We are supposed to attach all the views we found (int temp)

  161. // to root. Do that now.

  162. if (root != null && attachToRoot) {

  163. root.addView(temp, params);

  164. }

  165.  
  166. // Decide whether to return the root that was passed in or the

  167. // top view found in xml.

  168. if (root == null || !attachToRoot) {

  169. result = temp;

  170. }

  171. }

  172.  
  173. } catch (XmlPullParserException e) {

  174. InflateException ex = new InflateException(e.getMessage());

  175. ex.initCause(e);

  176. throw ex;

  177. } catch (Exception e) {

  178. InflateException ex = new InflateException(

  179. parser.getPositionDescription()

  180. + ": " + e.getMessage());

  181. ex.initCause(e);

  182. throw ex;

  183. } finally {

  184. // Don't retain static reference on context.

  185. mConstructorArgs[0] = lastContext;

  186. mConstructorArgs[1] = null;

  187. }

  188.  
  189. Trace.traceEnd(Trace.TRACE_TAG_VIEW);

  190.  
  191. return result;

  192. }

  193. }

根據以上源碼我們會發現,重載的四個方法歸根結底最後調用的都是這個方法:

 

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

該方法和以下方法的區別在於下面的方法根據提供的resource來獲得相應的parser,然後再調用上面的方法。

 

 public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

 

 

所以我們主要來分析這個方法。參數詳解:

第一個參數:int resource,表示需要加載佈局文件的id,意思是需要將這個佈局文件中加載到Activity中來操作;

第二個參數:ViewGroup root,表示需要附加到resource資源文件的根控件。說明:調用inflate方法後會得到一個View對象,root參數就是接收該 View對象的容器;

第三個參數:boolean attachToRoot, 表示是否把inflate得到的View對象添加到root中,該參數爲false時,表示不直接添加到root中;該參數爲true時,表示直接添加到root中;

下面同過具體代碼來說明:

activity_main.xml

 


 
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. android:layout_width="fill_parent"

  4. android:layout_height="fill_parent"

  5. android:orientation="vertical">

  6.  
  7. <TextView

  8. android:layout_width="fill_parent"

  9. android:layout_height="wrap_content"

  10. android:text="@string/hello" />

  11.  
  12. <FrameLayout

  13. android:id="@+id/fl_container"

  14. android:layout_width="match_parent"

  15. android:layout_height="wrap_content">

  16.  
  17. </FrameLayout>

  18.  
  19. </LinearLayout>


inflate_view_layout.xml

 

 


 
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. android:layout_width="match_parent"

  4. android:layout_height="match_parent"

  5. android:orientation="vertical">

  6.  
  7. <CheckBox

  8. android:id="@+id/checkBox1"

  9. android:layout_width="wrap_content"

  10. android:layout_height="wrap_content"

  11. android:text="@string/checkBox" />

  12.  
  13. </LinearLayout>

 

 

MainActivity.java

 


 
  1. package com.rainmonth.inflatemethoddemo;

  2.  
  3. import android.support.v7.app.AppCompatActivity;

  4. import android.os.Bundle;

  5. import android.text.Layout;

  6. import android.view.LayoutInflater;

  7. import android.view.View;

  8. import android.widget.FrameLayout;

  9.  
  10. public class MainActivity extends AppCompatActivity {

  11.  
  12. @Override

  13. protected void onCreate(Bundle savedInstanceState) {

  14. super.onCreate(savedInstanceState);

  15. setContentView(R.layout.activity_main);

  16. FrameLayout frameLayout = (FrameLayout) findViewById(R.id.fl_container);

  17.  
  18. // 第三個參數設置爲false

  19. View inflateView = LayoutInflater.from(this).inflate(R.layout.inflate_view_layout, frameLayout, false);

  20.  
  21. // 第三個參數設置爲true,默認爲true

  22. // View inflateView = LayoutInflater.from(this).inflate(R.layout.inflate_view_layout, frameLayout, true);

  23. }

  24. }


第三個參數爲false時的運行結果如下:

 

\
 

此時,inflateView 對應的佈局內容並未呈現出來。

第三個參數爲true時的運行結果如下:

\

此時inflateView對應的佈局內容呈現出來了。由此可見第三個參數的作用就是是否把inflate出來的參數加入到root容器中,false時不添加;true時添加

爲了驗證結論,我們在第三個參數爲false時在添加一下代碼:

 

frameLayout.addView(inflateView);

我們發現其現實結果同第三個參數設置爲true時是一樣的,所以我們的結論得到了驗證。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章