Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 基礎入門教程——10.8 LayoutInflater(布局服務)

編輯:關於 Android 程式設計

Android 基礎入門教程——10.8 LayoutInflater(布局服務)

標籤:Android 基礎入門教程


本節引言

本節介紹 Android 系統服務中的 LayoutInflater(布局服務)。說到布局,大家第一時間想到的多半是寫好一個布局 XML,再呼叫 Activity 的 setContentView() 加載並顯示。其實它底層走的正是 LayoutInflater,用 Android 內建的 Pull 解析器解析布局。它常用於動態加載布局或動態添加控件,下面我們就來看看它在實際開發中的一些用法。


1. LayoutInflater 相關介紹

1)Layout 是什麼

它是一個用於加載布局的系統服務,負責把與布局 XML 對應的 View 物件例項化。它不能直接 new,需要透過 getLayoutInflater() 或 getSystemService() 取得與當前 Context 綁定的 LayoutInflater 例項。


2)LayoutInflater 的用法

①取得 LayoutInflater 例項的三種方式:

LayoutInflater inflater1 = LayoutInflater.from(this);
LayoutInflater inflater2 = getLayoutInflater();
LayoutInflater inflater3 = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

後兩者底層其實走的都是第一種方式。

②加載布局的方法:

public View inflate(int resource, ViewGroup root, boolean attachToRoot)
三個參數依次為:①要加載的布局資源 id;②為該布局外層再嵌套一層父布局,不需要時寫 null 即可;③是否為加載布局的最外層套一層 root 布局。若 root 為 null,attachToRoot 便失去作用;若 root 不為 null 且 attachToRoot 為 true,會在最外層嵌套一層 root;為 false 則 root 失效。簡單理解就是:是否為加載的布局添加一個 root 外層容器。


③透過 LayoutInflater.LayoutParams 設定相關屬性:例如 RelativeLayout 可以透過 addRule 添加位置規則、設定 margin 等,具體取決於你的需求。


2. 純 Java 代碼加載布局

我們早已習慣用 XML 生成布局,但有些特定場景需要用 Java 代碼動態添加組件。不過並不建議完全用 Java 代碼編寫頁面布局:一方面代碼量大、容易混亂,另一方面不利於業務分離。更好的做法是先用 XML 完成布局,再用 Java 代碼修改其中組件,必要時才動態添加。

純 Java 代碼加載布局的流程

Step 1:建立容器與組件,例如 LinearLayout ly = new LinearLayout(this);、Button btnOne = new Button(this);

Step 2:為容器或組件設定屬性,例如 ly.setOrientation(LinearLayout.VERTICAL);、btnOne.setText("按鈕1");。XML 中設定的屬性,通常在前面加上 set 即可,如 setPadding(左,上,右,下)。

Step 3:把組件添加到容器中,這時可能需要設定位置與大小,會用到 LayoutParams——可以把它看作封裝了位置與大小等資訊的「資訊包」。先示範設定大小:

LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

設定位置時通常考慮 RelativeLayout,用到 LayoutParams 的 addRule() 方法,可以添加多條規則。例如設定組件的對齊方式:

RelativeLayout rly = new RelativeLayout(this);
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
Button btnOne = new Button(this);
rly.addView(btnOne, lp2);

若要參照其他組件對齊(缺點是需要手動為參照組件設定 id),例如讓 btnTwo 位於 btnOne 下方並對齊父容器右側:

public class MainActivity extends Activity {
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RelativeLayout rly = new RelativeLayout(this);
        Button btnOne = new Button(this);
        btnOne.setText("按鈕1");
        Button btnTwo = new Button(this);
        btnTwo.setText("按鈕2");
        btnOne.setId(123); // 手動為按鈕1設定 id
        RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        rlp1.addRule(RelativeLayout.CENTER_IN_PARENT);
        RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        rlp2.addRule(RelativeLayout.BELOW, 123);
        rlp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        rly.addView(btnTwo, rlp2);
        rly.addView(btnOne, rlp1);
        setContentView(rly);
    }
}

Step 4:呼叫 setContentView() 加載布局物件即可。若想移除某容器中的 View,可呼叫容器.removeView(組件)。

執行截圖:


3. Java 代碼動態添加控件或加載 XML 布局

純 Java 代碼加載布局實際中用得不多,更多時候是動態添加 View 控件,或動態加載 XML 布局。

1)Java 代碼動態增加 View

動態添加組件有兩種寫法,區別在於是否需要先 setContentView() 加載布局檔。先寫個 activity_main.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="我是 xml 文件加載的布局" />
</RelativeLayout>

第一種:先用 inflate() 加載布局,再添加按鈕,最後 setContentView():

public class MainActivity extends Activity {
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button btnOne = new Button(this);
        btnOne.setText("我是動態添加的按鈕");
        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        lp2.addRule(RelativeLayout.CENTER_IN_PARENT);
        LayoutInflater inflater = LayoutInflater.from(this);
        RelativeLayout rly = (RelativeLayout) inflater.inflate(R.layout.activity_main, null)
                .findViewById(R.id.RelativeLayout1);
        rly.addView(btnOne, lp2);
        setContentView(rly);
    }
}

第二種:先 setContentView() 加載布局,再用 findViewById 找到外層容器並添加按鈕:

public class MainActivity extends Activity {
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnOne = new Button(this);
        btnOne.setText("我是動態添加的按鈕");
        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        lp2.addRule(RelativeLayout.CENTER_IN_PARENT);
        RelativeLayout rly = (RelativeLayout) findViewById(R.id.RelativeLayout1);
        rly.addView(btnOne, lp2);
    }
}

分析總結:兩種寫法都是先建立按鈕,再建立 LayoutParams 設定大小與位置。第一種透過 inflate() 加載布局取得外層容器後 addView,最後 setContentView();第二種因已用 setContentView() 加載布局,可直接 findViewById 取得容器再 addView。另外要注意,setContentView() 設置的視圖節點是整個 XML 的根節點。

2)Java 代碼動態加載 XML 布局

接下來動態加載一個 XML 布局。主布局 activity_main.xml:

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

被動態加載的 inflate.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/ly_inflate"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是 Java 代碼加載的布局" />
</LinearLayout>

在 MainActivity.java 中動態加載 XML 布局:

public class MainActivity extends Activity {
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final LayoutInflater inflater = LayoutInflater.from(this);
        final RelativeLayout rly = (RelativeLayout) findViewById(R.id.RelativeLayout1);
        Button btnLoad = (Button) findViewById(R.id.btnLoad);
        btnLoad.setOnClickListener(new OnClickListener() {
            @Override public void onClick(View v) {
                LinearLayout ly = (LinearLayout) inflater.inflate(R.layout.inflate_ly, null, false)
                        .findViewById(R.id.ly_inflate);
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                lp.addRule(RelativeLayout.CENTER_IN_PARENT);
                rly.addView(ly, lp);
            }
        });
    }
}

執行截圖:

代碼分析:①取得容器物件 rly;②取得 Inflater 物件並加載被添加布局的 XML,透過 findViewById 找到最外層根節點;③為該容器設定大小與位置;④添加到外層容器中。


4. LayoutInflater 的 inflate() 方法源碼

最後附上 inflate() 方法源碼,有興趣可以看看,本質上就是 Pull 解析。

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;
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved