編輯: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:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:id="@+id/main_layout"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- </LinearLayout>
這個布局裡只有一個空的 LinearLayout,什麼控件都沒有,所以界面上不會顯示任何東西。
再定義一個布局文件 button_layout.xml:
- <Button xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" >
- </Button>
這裡只有一個 Button。現在我們要設法用 LayoutInflater 把 button_layout 添加到主布局的 LinearLayout 中。修改 MainActivity:
- public class MainActivity extends Activity {
- private LinearLayout mainLayout;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- mainLayout = (LinearLayout) findViewById(R.id.main_layout);
- LayoutInflater layoutInflater = LayoutInflater.from(this);
- View buttonLayout = layoutInflater.inflate(R.layout.button_layout, null);
- mainLayout.addView(buttonLayout);
- }
- }
這裡先拿到 LayoutInflater 實例,調用 inflate() 加載 button_layout,最後用 LinearLayout 的 addView() 把它添加進去。運行後,Button 便顯示了出來,說明我們確實借助 LayoutInflater 成功把布局添加到了 LinearLayout 中。LayoutInflater 廣泛應用於需要動態添加 View 的場景,比如在 ScrollView 和 ListView 中就常見它的身影。
僅僅知道如何使用顯然滿足不了求知欲,知其然還要知其所以然,接下來從源碼角度看它到底如何運作。無論你調用哪個 inflate() 重載,最終都會輾轉調到這段代碼:
- public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
- synchronized (mConstructorArgs) {
- final AttributeSet attrs = Xml.asAttributeSet(parser);
- mConstructorArgs[0] = mContext;
- View result = root;
- try {
- int type;
- while ((type = parser.next()) != XmlPullParser.START_TAG &&
- type != XmlPullParser.END_DOCUMENT) {
- }
- if (type != XmlPullParser.START_TAG) {
- throw new InflateException(parser.getPositionDescription()
- + ": No start tag found!");
- }
- final String name = parser.getName();
- if (TAG_MERGE.equals(name)) {
- if (root == null || !attachToRoot) {
- throw new InflateException("merge can be used only with a valid "
- + "ViewGroup root and attachToRoot=true");
- }
- rInflate(parser, root, attrs);
- } else {
- View temp = createViewFromTag(name, attrs);
- ViewGroup.LayoutParams params = null;
- if (root != null) {
- params = root.generateLayoutParams(attrs);
- if (!attachToRoot) {
- temp.setLayoutParams(params);
- }
- }
- rInflate(parser, temp, attrs);
- if (root != null && attachToRoot) {
- root.addView(temp, params);
- }
- if (root == null || !attachToRoot) {
- result = temp;
- }
- }
- } catch (XmlPullParserException e) {
- InflateException ex = new InflateException(e.getMessage());
- ex.initCause(e);
- throw ex;
- } catch (IOException e) {
- InflateException ex = new InflateException(
- parser.getPositionDescription()
- + ": " + e.getMessage());
- ex.initCause(e);
- throw ex;
- }
- return result;
- }
- }
從這裡可以清楚看到,LayoutInflater 本質上就是用 Android 提供的 pull 解析方式來解析布局文件。不熟悉 pull 解析的朋友可以自行搜索,教程很多。這裡注意第 23 行,調用了 createViewFromTag() 並把節點名和屬性傳了進去。看名字就能猜到,它是根據節點名創建 View 對象的——沒錯,它內部又會調用 createView(),用反射的方式創建 View 實例並返回。
不過這裡只創建了根布局的實例,接下來第 31 行調用 rInflate() 遍歷根布局下的子元素:
- private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs)
- throws XmlPullParserException, IOException {
- final int depth = parser.getDepth();
- int type;
- while (((type = parser.next()) != XmlPullParser.END_TAG ||
- parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
- if (type != XmlPullParser.START_TAG) {
- continue;
- }
- final String name = parser.getName();
- if (TAG_REQUEST_FOCUS.equals(name)) {
- parseRequestFocus(parser, parent);
- } else if (TAG_INCLUDE.equals(name)) {
- if (parser.getDepth() == 0) {
- throw new InflateException("<include /> cannot be the root element");
- }
- parseInclude(parser, parent, attrs);
- } else if (TAG_MERGE.equals(name)) {
- throw new InflateException("<merge /> must be the root element");
- } else {
- final View view = createViewFromTag(name, attrs);
- final ViewGroup viewGroup = (ViewGroup) parent;
- final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
- rInflate(parser, view, attrs);
- viewGroup.addView(view, params);
- }
- }
- parent.onFinishInflate();
- }
第 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:
- <Button xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="300dp"
- android:layout_height="80dp"
- android:text="Button" >
- </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 理所當然沒作用。想改變按鈕大小,方法有很多,最簡單的就是在外層再嵌套一個布局:
- <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <Button
- android:layout_width="300dp"
- android:layout_height="80dp"
- android:text="Button" >
- </Button>
- </RelativeLayout>
此時 Button 處於 RelativeLayout 之中,layout_width 和 layout_height 便有了作用。當然,處於最外層的 RelativeLayout,它的 layout_width 和 layout_height 又會失去作用。重新運行,按鈕終於變大了。
看到這裡,或許有朋友心中會有個巨大的疑惑:不對呀!平時在 Activity 中指定布局文件時,最外層的布局是可以指定大小的呀。確實,這主要是因為在 setContentView() 方法中,Android 會自動在布局最外層再嵌套一個 FrameLayout,所以 layout_width 和 layout_height 才有效果。我們來驗證一下,修改 MainActivity:
- public class MainActivity extends Activity {
- private LinearLayout mainLayout;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- mainLayout = (LinearLayout) findViewById(R.id.main_layout);
- ViewParent viewParent = mainLayout.getParent();
- Log.d("TAG", "the parent of mainLayout is " + viewParent);
- }
- }
這裡先拿到 activity_main 中最外層的 LinearLayout,再調用 getParent() 獲取它的父布局並打印出來。運行後可以看到,LinearLayout 的父布局確實是一個 FrameLayout,而這個 FrameLayout 正是系統自動幫我們添加的。
說到這,雖然 setContentView() 大家都會用,但實際上 Android 界面顯示的原理比我們看到的複雜得多。任何一個 Activity 中顯示的界面主要由兩部分組成:標題欄和內容布局。標題欄就是很多界面頂部那部分,可以通過代碼控制是否顯示;而內容布局是一個 id 為 content 的 FrameLayout,我們調用 setContentView() 傳入的布局其實就是放進這個 FrameLayout 裡的——這也是為什麼方法名叫 setContentView(),而不是 setView()。
好了,今天就講到這裡。支持的、吐槽的、有疑問的以及路過打醬油的朋友,盡管留言吧 ^v^ 感興趣的朋友可以繼續閱讀下一篇。
Android 開發實作:ListView 與 GridView 用法全解析
ListView 與 GridView 是 Android 開發裡最常被使用的兩個檢視元件,兩者都必須搭配 Adapter 才能發揮作用。本文以兩個可運行的實例,分別說明
Android Wear 計時器開發(一):為什麼不能照搬手機的設計思路
早在 2013 年 12 月,我曾寫過一系列文章,示範如何開發一款讓用戶在足球比賽中記錄停表時間的 App。等到 Android Wear 問世,把這樣的應用搬到智慧手錶
Android Permission 權限級別與組件保護
Android 權限不僅用於安裝宣告,也可用於保護組件間通訊。不同 protectionLevel 會影響授權方式與風險提示。常見權限級別normal 屬於低風險權限,安
Android ApiDemo 系列四:自訂 Dialog 主題
在 Android 中,Activity 的外觀可以透過 Theme 調整。ApiDemo 的 Custom Dialog 範例將一個 Activity 套用自訂主題,使