SoFunction
Updated on 2025-03-11

Android layout performance optimization: Loading View on Demand

Sometimes there are some complex layouts that are rarely used in the application. Reloading them when needed can reduce memory consumption and also speed up the rendering of the interface.

Define ViewStub

ViewStub is a lightweight View that has no height and width and does not draw anything. So its loading and unloading costs are very low. Each ViewStub can use the android:layout property to specify the layout to be loaded.

The following ViewStub is used for loading a semi-transparent ProgressBar. It will only be displayed when a new job begins.

<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" />

Load ViewStub

When you need to load the layout specified by ViewStub, you can use the setVisibility() method or the inflate() method, and the effects of both are the same.

((ViewStub) findViewById(.stub_import)).setVisibility();
// or
View importPanel = ((ViewStub) findViewById(.stub_import)).inflate();

Note: The inflate() method will return a View when it is loaded. So you don't need to use findViewById() to find the Root View for this layout.
Once the View hosted by ViewStub is loaded, ViewStub will no longer be part of the View hierarchy. It will be replaced by the loaded layout and will change the ID of the layout to the ID specified by the android:inflatedId property of ViewStub.

Note: The disadvantage of ViewStub is that it does not currently support the root View to load the layout as the < merge/> tag.

The above is the Android layout performance optimization that the editor introduced to you, loading View on demand. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!