Updated 16 June 2019
ViewStub:
A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime.
When a ViewStub is made visible, or when inflate() is invoked, then layout resource is inflated. ViewStub replaces itself in its parent with the inflated View or Views. ViewStub exists in the view hierarchy until setVisibility(int)
or inflate()
 is invoked.
You can reduce memory usage and speed up rendering by loading the views only when they are needed.
Define ViewStub in XML file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <import type="android.view.View" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--Other Views--> <ViewStub android:id="@+id/nav_drawer_user_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> <!--Other Views--> </LinearLayout> </layout> |
Inflate ViewStub:Â
We can specify layout at run time (viewStub!!.layoutResource) or in XML layout (android: layout)Â attribute. A ViewStub can be load by using visible, or inflate().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v4.app.Fragment import android.view.View import android.view.ViewStub import com.webkul.mobikul.fragments.NavDrawerStartFragment import com.webkul.mobikulmp.databinding.LayoutSellerMenusBinding class ViewStubs : Fragment() { override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if(some condition){ updateMenu() } } fun updateMenu() { mContentViewBinding.navDrawerUserView.viewStub!! .setOnInflateListener( object : ViewStub.OnInflateListener { override fun onInflate(stub: ViewStub, inflated: View) { val binding: LayoutUserMenusBinding? = DataBindingUtil.bind(inflated) } }) //Set layout resouce mContentViewBinding.navDrawerUserView. viewStub!!.layoutResource = R.layout.layout_user_menus if (!mContentViewBinding.navDrawerUserView.isInflated) { // inflate you layout after setting layout resouce mContentViewBinding.navDrawerUserView.viewStub!!.inflate() } } } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
2 comments