English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Sometimes there may be some complex layouts that are rarely used in applications. Loading them only when needed can reduce memory consumption and also speed up the rendering speed of the interface.
Define ViewStub
ViewStub is a lightweight View that has no width and height and does not draw anything. Therefore, its cost of loading and unloading is very low. Each ViewStub can specify the layout to be loaded using the android:layout attribute.
This ViewStub is used to load a semi-transparent ProgressBar. It is only displayed when a new task starts.
<ViewStub android:id="@+id/stub_import" 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(View.VISIBLE) method or the inflate() method, both of which have the same effect.
((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE); // or View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();
Note: The inflate() method returns a View when loading is complete. Therefore, there is no need to use findViewById() to find the Root View of this layout.
Once the ViewStub-managed View is loaded, the ViewStub will no longer be part of the View hierarchy. It will be replaced by the loaded layout, and the ID of the layout will be changed to the ID specified by the android:inflatedId attribute of ViewStub.
Note: The缺点of ViewStub is that it currently does not support the root View of the layout to be loaded as < merge/> Tag.
The above-mentioned is the introduction of Android layout performance optimization by on-demand loading of View given by the editor. I hope it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. Also, I would like to express my sincere gratitude to everyone for their support of the Nahan tutorial website!