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

Android View(一):LayoutInflater 原理深度剖析

編輯:Android 開發實例

接觸 Android 久一點的朋友,對 LayoutInflater 應該都不陌生,都知道它是用來加載布局的。而剛入門的朋友可能對它比較陌生,因為加載布局的活儿通常都在 Activity 裡調用 setContentView() 完成。其實 setContentView() 內部也是靠 LayoutInflater 來加載布局的,只不過那部分源碼是 internal 的,不太容易看到。今天我們就把 LayoutInflater 的工作流程好好剖析一遍,說不定還能解開某些困擾你多年的疑惑。

先看看它的基本用法,非常簡單。首先要拿到 LayoutInflater 的實例,有兩種寫法。第一種:

 LayoutInflater layoutInflater = LayoutInflater.from(context);

第二種:

 LayoutInflater layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

其實第一種就是第二種的簡化封裝。拿到實例後,調用它的 inflate() 方法即可加載布局:

 layoutInflater.inflate(resourceId, root);

inflate() 一般接收兩個參數:第一個是要加載的布局 id,第二個是指給該布局再外層嵌套一層父布局,不需要就傳 null。這樣便創建出一個布局實例,之後把它添加到指定位置就能顯示了。

下面用一個小例子直觀地感受一下。假設項目中 MainActivity 對應的布局文件叫 activity_main.xml:

  1. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     android:id="@+id/main_layout" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" > 
  5.  
  6. </LinearLayout> 

這個布局裡只有一個空的 LinearLayout,什麼控件都沒有,所以界面上不會顯示任何東西。

再定義一個布局文件 button_layout.xml:

  1. <Button xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     android:layout_width="wrap_content" 
  3.     android:layout_height="wrap_content" 
  4.     android:text="Button" > 
  5.  
  6. </Button> 

這裡只有一個 Button。現在我們要設法用 LayoutInflater 把 button_layout 添加到主布局的 LinearLayout 中。修改 MainActivity:

  1. public class MainActivity extends Activity {  
  2.  
  3.     private LinearLayout mainLayout;  
  4.  
  5.     @Override 
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_main);  
  9.         mainLayout = (LinearLayout) findViewById(R.id.main_layout);  
  10.         LayoutInflater layoutInflater = LayoutInflater.from(this);  
  11.         View buttonLayout = layoutInflater.inflate(R.layout.button_layout, null);  
  12.         mainLayout.addView(buttonLayout);  
  13.     }  
  14.  
  15. }  

這裡先拿到 LayoutInflater 實例,調用 inflate() 加載 button_layout,最後用 LinearLayout 的 addView() 把它添加進去。運行後,Button 便顯示了出來,說明我們確實借助 LayoutInflater 成功把布局添加到了 LinearLayout 中。LayoutInflater 廣泛應用於需要動態添加 View 的場景,比如在 ScrollView 和 ListView 中就常見它的身影。

僅僅知道如何使用顯然滿足不了求知欲,知其然還要知其所以然,接下來從源碼角度看它到底如何運作。無論你調用哪個 inflate() 重載,最終都會輾轉調到這段代碼:

  1. public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {  
  2.     synchronized (mConstructorArgs) {  
  3.         final AttributeSet attrs = Xml.asAttributeSet(parser);  
  4.         mConstructorArgs[0] = mContext;  
  5.         View result = root;  
  6.         try {  
  7.             int type;  
  8.             while ((type = parser.next()) != XmlPullParser.START_TAG && 
  9.                     type != XmlPullParser.END_DOCUMENT) {  
  10.             }  
  11.             if (type != XmlPullParser.START_TAG) {  
  12.                 throw new InflateException(parser.getPositionDescription() 
  13.                         + ": No start tag found!");  
  14.             }  
  15.             final String name = parser.getName();  
  16.             if (TAG_MERGE.equals(name)) {  
  17.                 if (root == null || !attachToRoot) {  
  18.                     throw new InflateException("merge can be used only with a valid " 
  19.                             + "ViewGroup root and attachToRoot=true");  
  20.                 }  
  21.                 rInflate(parser, root, attrs);  
  22.             } else {  
  23.                 View temp = createViewFromTag(name, attrs);  
  24.                 ViewGroup.LayoutParams params = null;  
  25.                 if (root != null) {  
  26.                     params = root.generateLayoutParams(attrs);  
  27.                 if (!attachToRoot) {  
  28.                         temp.setLayoutParams(params);  
  29.                 }  
  30.                }  
  31.                rInflate(parser, temp, attrs);  
  32.                if (root != null && attachToRoot) {  
  33.                   root.addView(temp, params);  
  34.                }  
  35.                if (root == null || !attachToRoot) {  
  36.                   result = temp;  
  37.                }  
  38.             }  
  39.         } catch (XmlPullParserException e) {  
  40.             InflateException ex = new InflateException(e.getMessage());  
  41.             ex.initCause(e);  
  42.             throw ex;  
  43.         } catch (IOException e) {  
  44.             InflateException ex = new InflateException(  
  45.                     parser.getPositionDescription()  
  46.                     + ": " + e.getMessage());  
  47.             ex.initCause(e);  
  48.             throw ex;  
  49.         }  
  50.         return result;  
  51.     }  
  52. }  

從這裡可以清楚看到,LayoutInflater 本質上就是用 Android 提供的 pull 解析方式來解析布局文件。不熟悉 pull 解析的朋友可以自行搜索,教程很多。這裡注意第 23 行,調用了 createViewFromTag() 並把節點名和屬性傳了進去。看名字就能猜到,它是根據節點名創建 View 對象的——沒錯,它內部又會調用 createView(),用反射的方式創建 View 實例並返回。

不過這裡只創建了根布局的實例,接下來第 31 行調用 rInflate() 遍歷根布局下的子元素:

  1. private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs) 
  2.         throws XmlPullParserException, IOException {  
  3.     final int depth = parser.getDepth();  
  4.     int type;  
  5.     while (((type = parser.next()) != XmlPullParser.END_TAG || 
  6.             parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {  
  7.         if (type != XmlPullParser.START_TAG) {  
  8.             continue;  
  9.         }  
  10.         final String name = parser.getName();  
  11.         if (TAG_REQUEST_FOCUS.equals(name)) {  
  12.             parseRequestFocus(parser, parent);  
  13.         } else if (TAG_INCLUDE.equals(name)) {  
  14.             if (parser.getDepth() == 0) {  
  15.                 throw new InflateException("<include /> cannot be the root element");  
  16.             }  
  17.             parseInclude(parser, parent, attrs);  
  18.         } else if (TAG_MERGE.equals(name)) {  
  19.             throw new InflateException("<merge /> must be the root element");  
  20.         } else {  
  21.             final View view = createViewFromTag(name, attrs);  
  22.             final ViewGroup viewGroup = (ViewGroup) parent;  
  23.             final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);  
  24.             rInflate(parser, view, attrs);  
  25.             viewGroup.addView(view, params);  
  26.         }  
  27.     }  
  28.     parent.onFinishInflate();  
  29. } 

第 21 行同樣用 createViewFromTag() 創建 View 實例,第 24 行遞歸調用 rInflate() 查找其子元素,每次遞歸完成後就把這個 View 添加到父布局中。這樣,整個布局文件解析完成後便形成了一個完整的 DOM 結構,最終返回最頂層的根布局,inflate() 過程就此結束。

細心的朋友可能注意到,inflate() 還有個接收三個參數的重載:

 inflate(int resource, ViewGroup root, boolean attachToRoot)

那第三個參數 attachToRoot 是什麼意思?仔細讀上面的源碼其實就能自己分析出來,這裡先拋出結論,感興趣的朋友可以回頭對照源碼驗證:

1. 若 root 為 null,attachToRoot 將失去作用,設任何值都無意義。

2. 若 root 不為 null 且 attachToRoot 為 true,會在加載的布局最外層再嵌套一層 root 布局。

3. 若 root 不為 null 且 attachToRoot 為 false,則 root 參數失去作用。

4. 在不設置 attachToRoot 的情況下,若 root 不為 null,attachToRoot 默認為 true。

原理搞清楚了,可你該不滿足了吧——例子裡的按鈕看著有點小,想調大一點?簡單,修改 button_layout.xml:

  1. <Button xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     android:layout_width="300dp" 
  3.     android:layout_height="80dp" 
  4.     android:text="Button" > 
  5.  
  6. </Button> 

把寬度改成 300dp、高度改成 80dp,這樣夠大了吧?重新運行——咦?按鈕還是原來的大小,毫無變化!我以為不夠大再改大一點,還是一樣!

其實不管你怎麼改 layout_width 和 layout_height 都不會有效果,因為這兩個值現在完全失去了作用。平時我們用它們設置 View 大小一直很正常,好像它們就是用來設 View 大小的。但實際不然——它們其實是用來設置 View「在布局中」的大小。也就是說,View 必須先存在於某個布局裡,之後 layout_width 設為 match_parent 表示寬度填滿布局,設為 wrap_content 表示剛好包住內容,設為具體數值則寬度變成該值。這也是為什麼叫 layout_width 而不是 width。

回看 button_layout.xml,很明顯 Button 目前不存在於任何布局中,所以 layout_width 和 layout_height 理所當然沒作用。想改變按鈕大小,方法有很多,最簡單的就是在外層再嵌套一個布局:

  1. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     android:layout_width="match_parent" 
  3.     android:layout_height="match_parent" > 
  4.  
  5.     <Button 
  6.         android:layout_width="300dp" 
  7.         android:layout_height="80dp" 
  8.         android:text="Button" > 
  9.     </Button> 
  10.  
  11. </RelativeLayout> 

此時 Button 處於 RelativeLayout 之中,layout_width 和 layout_height 便有了作用。當然,處於最外層的 RelativeLayout,它的 layout_width 和 layout_height 又會失去作用。重新運行,按鈕終於變大了。

看到這裡,或許有朋友心中會有個巨大的疑惑:不對呀!平時在 Activity 中指定布局文件時,最外層的布局是可以指定大小的呀。確實,這主要是因為在 setContentView() 方法中,Android 會自動在布局最外層再嵌套一個 FrameLayout,所以 layout_width 和 layout_height 才有效果。我們來驗證一下,修改 MainActivity:

  1. public class MainActivity extends Activity {  
  2.  
  3.     private LinearLayout mainLayout;  
  4.  
  5.     @Override 
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_main);  
  9.         mainLayout = (LinearLayout) findViewById(R.id.main_layout);  
  10.         ViewParent viewParent = mainLayout.getParent();  
  11.         Log.d("TAG", "the parent of mainLayout is " + viewParent);  
  12.     }  
  13.  
  14. }  

這裡先拿到 activity_main 中最外層的 LinearLayout,再調用 getParent() 獲取它的父布局並打印出來。運行後可以看到,LinearLayout 的父布局確實是一個 FrameLayout,而這個 FrameLayout 正是系統自動幫我們添加的。

說到這,雖然 setContentView() 大家都會用,但實際上 Android 界面顯示的原理比我們看到的複雜得多。任何一個 Activity 中顯示的界面主要由兩部分組成:標題欄和內容布局。標題欄就是很多界面頂部那部分,可以通過代碼控制是否顯示;而內容布局是一個 id 為 content 的 FrameLayout,我們調用 setContentView() 傳入的布局其實就是放進這個 FrameLayout 裡的——這也是為什麼方法名叫 setContentView(),而不是 setView()。

好了,今天就講到這裡。支持的、吐槽的、有疑問的以及路過打醬油的朋友,盡管留言吧 ^v^ 感興趣的朋友可以繼續閱讀下一篇。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved