Android ViewStub Using Kotlin With Example

In this article, we will learn about android ViewStub using Kotlin. We will go through various example that demonstrates how to use different attributes of ViewStub. For example,

In this article, we will get answer to questions like –

  • What is ViewStub?
  • Why should we consider ViewStub while designing ui for any app?
  • What are possibilities using ViewStub while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin ViewStub Output Android ViewStub Using Kotlin Tutorial With Example

Tutorialwing Kotlin ViewStub Output

Getting Started

We can define android ViewStub widget as below –

ViewStub is invisible, zero-sized view that are used to inflate layout resource at run time.

Now, how do we use ViewStub in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as ViewStub. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android ViewStub Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using ViewStub in Kotlin

Follow steps below to use ViewStub in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">ViewStub</string>
        <string name="hide">HIDE</string>
        <string name="show">SHOW</string>
        <string name="sub_view">This view is inflated by ViewStub by calling either inflate() or setVisibility(true) method</string>
    </resources>
    
  • Create View That Replaces ViewStub on inflate() Call

    Now, we will create views that replaces viewStub when inflate() method is called. So, create an xml file, sub_item.xml, in res/layout folder. Open res/layout/sub_item.xml file and add below code into it.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    	xmlns:android="http://schemas.android.com/apk/res/android"
    	android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:background="@android:color/holo_blue_light"
    	android:gravity="center"
    	android:padding="10dp">
    
    	<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:gravity="center"
    		android:text="@string/sub_view"
    		android:textColor="@android:color/black"
    		android:textSize="18sp"/>
    
    </LinearLayout>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="20dp"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/btnHide"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hide"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <ViewStub
            android:id="@+id/viewStub"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout="@layout/sub_item"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/btnHide" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.viewstub
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.view.View
    import com.tutorialwing.viewstub.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    	private var isViewInflated =
    		true // Default state that represents viewStub has been replaced by sub view
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setupViewStub()
    	}
    
    	private fun setupViewStub() {
    		binding.viewStub.visibility = View.VISIBLE // or you can use viewStub.inflate()
    
    		binding.btnHide.setOnClickListener {
    			isViewInflated = !isViewInflated
    			binding.viewStub.visibility = if (isViewInflated) View.VISIBLE else View.GONE
    			binding.btnHide.text =
    				getString(if (isViewInflated) R.string.hide else R.string.show)
    		}
    	}
    }
    

Now, run the application. We will get output as below –

Tutorialwing Kotlin ViewStub Output Android ViewStub Using Kotlin Tutorial With Example

Tutorialwing Kotlin ViewStub Output

Different Attributes of ViewStub in XML

Now, we will see how to use different attributes of Android ViewStub using Kotlin to customise it –

Set Id of ViewStub

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of ViewStub using android:id attribute like below –

    <ViewStub
        android:id="@+id/viewStub_ID"
        />

Here, we have set id of ViewStub as viewStub_ID using android:id=”” attribute. So, if we need to reference this ViewStub, we need to use this id – viewStub_ID.
Learn to Set ID of ViewStub Dynamically

Set Width of ViewStub

We use android:layout_width=”” attribute to set width of ViewStub.
We can do it as below –

    <ViewStub
        android:id="@+id/viewStub_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of ViewStub Dynamically

Set Height of ViewStub

We use android:layout_height=”” attribute to set height of ViewStub.
We can do it as below –

    <ViewStub
        android:id="@+id/viewStub_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of ViewStub Dynamically

Set Padding of ViewStub

We use android:padding=”” attribute to set padding of ViewStub.
We can do it as below –

    <ViewStub
        android:id="@+id/viewStub_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in ViewStub using android:padding=”” attribute.
Learn to Set Padding of ViewStub Dynamically

Set Margin of ViewStub

We use android:layout_margin=”” attribute to set margin of ViewStub.
We can do it as below –

    <ViewStub
        android:id="@+id/viewStub_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in ViewStub using android:layout_margin=”” attribute.
Learn to Set Margin of ViewStub Dynamically

Set Background of ViewStub

We use android:background=”” attribute to set background of ViewStub.
We can do it as below –

    <ViewStub
        android:id="@+id/viewStub_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in ViewStub using android:background=”” attribute.
Learn to Set Background of ViewStub Dynamically

Set Visibility of ViewStub

We use android:visibility=”” attribute to set visibility of ViewStub.
We can do it as below –

    <ViewStub
        android:id="@+id/viewStub_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of ViewStub using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of ViewStub Dynamically

Till now, we have see how to use android ViewStub using Kotlin. We have also gone through different attributes of ViewStub to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android ViewStub Widget

Below are the various attributes that are used to customise android ViewStub Widget. However, you can check the complete list of attributes of ViewStub in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Some of the popular attributes of android ViewStub widget are –

Sr. XML Attributes Description
1 android:inflatedId Defines id of the inflated view by viewStub
2 android:layout Provides identifier of the layout resource to inflate when viewStub is visible or forced to do so(by calling inflate() method)

Some of the popular attributes of android viewStub inherited from View are –

Sr. XML Attributes Description
1 android:alpha Defines alpha of the view
2 android:background Defines background of the view
3 android:focusable Defines whether view can take focus or not
4 android:id Defines unique identifier of the view
5 android:padding Defines padding of view
6 android:visibility Defines whether this view is visible or not

We have seen different attributes of ViewStub and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is ViewStub, how can we use android ViewStub using Kotlin ? etc. We also went through different attributes of android ViewStub.

Leave a Reply