Android優化篇 ViewStub按需載入佈局
原文連結
更多教程
你將學到
1.ViewStub標籤的 使用姿勢
2.ViewStub標籤的 使用例子
3.ViewStub標籤的 使用注意點
ViewStub標籤的使用姿勢
- 步驟一:定義需要懶載入的佈局 test.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="100dp" android:background="#36e7ea" android:gravity="center" android:textSize="18sp" /> </LinearLayout>
- 步驟二:使用ViewStub引入要懶載入的佈局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button//點選按鈕時才載入下面的ViewStub佈局 android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="載入ViewStub" /> <ViewStub//這個佈局現在還不會被新增到佈局樹中 android:id="@+id/view_stub" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout="@layout/test" />//這裡指定要載入的佈局名字 </LinearLayout>
-
步驟三:使用程式碼按需載入上面的ViewStub佈局
這裡是點選按鈕的時候新增:
Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { View view = ((ViewStub)findViewById(R.id.view_stub)).inflate();//加載出來用view接收 TextView tv = (TextView) view.findViewById(R.id.text_view); //然後可以用view訪問它的子控制元件 tv.setText("ViewStub的使用"); } });
效果:
點選按鈕前:

點選按鈕後,出現了需要臨時載入的佈局:

ViewStub使用注意點
-
ViewStub物件只可以Inflate一次,之後ViewStub物件會被置為空。
所以,inflate一個ViewStub物件之後,就不能再inflate它了,否則會報錯:ViewStub must have a non-null ViewGroup viewParent。。

-
ViewStub不支援merge標籤,意味著你不能引入包含merge標籤的佈局到ViewStub中。
否則會報錯:android.view.InflateException: Binary XML file line #1: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true