Android ViewStub: Optimize Layout Performance
ViewStub is a lightweight implementation of a View, where a placeholder can be defined in the layout file and a real View can be dynamically filled at that location during runtime. This can help reduce the loading time and memory consumption of the layout file, especially useful in situations where certain Views need to be lazily loaded.
The steps for using ViewStub are as follows:
- In the layout file, define the ViewStub tag by specifying the layout attribute and id attribute, for example:
<ViewStub
android:id="@+id/stub"
android:layout="@layout/your_layout" />
- In the code, locate the ViewStub and load or display the actual View as needed.
ViewStub stub = findViewById(R.id.stub);
View inflatedView = stub.inflate();
// 设置真正View的内容
- If you only want to display the placeholder within the ViewStub without loading the actual View, you can call the setVisibility method, for example:
ViewStub stub = findViewById(R.id.stub);
stub.setVisibility(View.VISIBLE);
In general, the purpose of ViewStub is to delay loading and act as a placeholder, allowing dynamic loading of Views when needed, thus improving performance and memory efficiency.