SoFunction
Updated on 2025-04-10

Analyzing Android development optimization: Detailed explanation of the optimization of interface UI (III)

Sometimes, our page may contain some layouts, which are hidden by default. When the user triggers a certain operation, the hidden layout will be displayed. For example, we have an Activity to display a list of friends. After the user clicks on "Import" in Menu, a layout interface for importing friends will be displayed in the current Activity. From the perspective of requirements, this import function is generally not used by users. That is, most of the time, the layout of the imported friends will not be displayed. At this time, the delay loading function can be used.

ViewStub is a hidden, memory-free view object that can delay loading layout resource files at runtime. This layout resource file will be loaded only when ViewStub is set to visible or when the inflate() function is called. The ViewStub replaces itself in the parent container when the view is loaded. Therefore, ViewStub will remain in the view until setVisibility(int) or inflate() is called. The layout parameters of ViewStub will be added to the ViewStub parent container along with the number of views loaded. Similarly, you can also define or rename the Id value of the view object to be loaded by using the inflated Id property.

Please refer to the code snippet below.

Copy the codeThe code is as follows:

<ViewStub

android:

android:inflatedId="@+id/panel_import"

android:layout="@layout/progress_overlay"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_gravity="bottom" />


The defined ViewStub object can be found through the id "stub_import". After loading the layout resource file "progress_overlay", the ViewStub object is removed from its parent container. The View created by the layout resource "progress_overlay" can be found through the id "panel_import".


The recommended way to execute loading layout resource files is as follows:

Copy the codeThe code is as follows:

((ViewStub) findViewById(.stub_import)).setVisibility();

// or

View importPanel = ((ViewStub) findViewById(.stub_import)).inflate();


When inflate() is called, the ViewStub is replaced by the loaded view and returns the view object. This allows the application to do not need to perform additional findViewById() to get a reference to the loaded view.
Copy the codeThe code is as follows:

Experience sharing:

Use ViewStub to associate it with the layout resource file specified in the xml file, so that the layout resource file can be loaded when needed. When to load, don't load it once at the start. Doing this can not only speed up the application startup, but also save memory resources.