按需加载视图

有时,您的布局需要很少使用的复杂视图。无论是作品详情、进度指示器还是撤消消息,您都可以通过仅在需要时加载这些视图来减少内存使用量并加快渲染速度。

如果您有应用将来需要的复杂视图,可以通过为复杂且很少使用的视图定义 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 所示的内容:

空白屏幕的图片
图 1. 屏幕的初始状态:ViewStub 正在隐藏繁重的布局。

如果要加载 ViewStub 指定的布局,请通过调用 setVisibility(View.VISIBLE) 将其设置为可见,或调用 inflate()

以下代码段会模拟推迟加载。屏幕会照常在 ActivityonCreate() 中加载,然后会显示 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);
}
图 2. 可以看到深色主题布局。

在可见或膨胀后,ViewStub 元素将不再是视图层次结构的一部分。它会被替换为经过膨胀的布局,并且该布局的根视图的 ID 由 ViewStubandroid:inflatedId 属性指定。为 ViewStub 指定的 ID android:id 仅在 ViewStub 布局可见或膨胀之前有效。

如需详细了解此主题,请参阅博文使用桩进行优化