有時您的版面配置需要用到不常用的複雜檢視畫面。無論是項目詳細資料、進度指標或復原訊息,您都可以只在需要時載入檢視畫面,藉此降低記憶體用量並加快轉譯速度。
只要針對應用程式未來需要的複雜檢視畫面定義 ViewStub
,您就可以延遲載入資源,方法是針對複雜和很少使用的檢視畫面定義。
定義 ViewStub
ViewStub
是沒有尺寸的輕量視圖,不會繪製任何內容或參與版面配置。因此,需要少量資源即可加載及離開檢視區塊階層。每個 ViewStub
都包含 android:layout
屬性,用於指定要加載的版面配置。
假設您想在應用程式後期的使用者歷程中載入某個版面配置:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:src="@drawable/logo" android:layout_width="match_parent" android:layout_height="match_parent"/> </FrameLayout>
您可以使用下列 ViewStub
延後載入。如要顯示或載入任何內容,您必須使其顯示推薦的版面配置:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root" android:layout_width="match_parent" android:layout_height="match_parent"> <ViewStub android:id="@+id/stub_import" android:inflatedId="@+id/panel_import" android:layout="@layout/heavy_layout_we_want_to_postpone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> </FrameLayout>
載入 ViewStub 版面配置
上一節的程式碼片段會產生類似圖 1 的內容:

ViewStub
會隱藏大量版面配置。如要載入 ViewStub
指定的版面配置,請呼叫 setVisibility(View.VISIBLE)
或呼叫 inflate()
,將其設為可見。
以下程式碼片段模擬了延遲載入。螢幕會照常在 Activity
和 onCreate()
中載入,然後顯示 heavy_layout_we_want_to_postpone
版面配置:
Kotlin
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_old_xml) Handler(Looper.getMainLooper()) .postDelayed({ findViewById<View>(R.id.stub_import).visibility = View.VISIBLE // Or val importPanel: View = findViewById<ViewStub>(R.id.stub_import).inflate() }, 2000) }
Java
@Override void onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_old_xml); Handler(Looper.getMainLooper()) .postDelayed({ findViewById<View>(R.id.stub_import).visibility = View.VISIBLE // Or val importPanel: View = findViewById<ViewStub>(R.id.stub_import).inflate() }, 2000); }

顯示或加載後,ViewStub
元素不再是檢視區塊階層的一部分。這會由加載的版面配置取代,而該版面配置的根層級檢視畫面 ID 則由 ViewStub
的 android:inflatedId
屬性指定。為 ViewStub
指定的 ID android:id
只有在顯示或加載 ViewStub
版面配置之前才會生效。
如要進一步瞭解這個主題,請參閱「使用虛設常式進行最佳化」這篇網誌文章。