Create An Android ViewStub Programmatically in Kotlin

In this article, we will learn how to create android ViewStub programmatically in Kotlin. We will go through various steps that explains how to create ViewStub and add it in kotlin file, use different attributes to customise it etc. in any android application. For example, how to set text in ViewStub programmatically, how to set id of ViewStub, how to capitalise text of ViewStub dynamically etc. We will get answer to all such questions in this post.

Learn to use Different Attributes of ViewStub in XML File to Customize it.

Output

Tutorialwing Kotlin Dynamic ViewStub Output Android ViewStub Programmatically in Kotlin Tutorial With Example

Tutorialwing Kotlin Dynamic 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

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 DynamicViewStub. 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 ViewStub in 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.

Since we have a new project, we will modify the xml and class file to use ViewStub programmatically in kotlin. Please follow the steps below.

2. Modify Values Folder

Open res/values/strings.xml file. Add below code into it.

<resources>
    <string name="app_name">DynamicViewStub</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>

Other values folders have not been changed. So, we are not going to mention it here.

3. Create Views That replaces ViewStub On inflate() Call

Now, we will create an xml file, named sub_item.xml, that are inflated when viewStub.inflate() method is called. Then, 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>

4. Modify Layout Folder

Open res/layout/activity_main.xml file. Add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/rootContainer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <Button
        android:id="@+id/btnShowHide"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hide"
        android:layout_marginTop="20dp"/>

</LinearLayout>

Note that LinearLayout has id rootContainer. In Kotlin file, we will create ViewStub Dynamically and add it into this LinearLayout having id rootContainer.

5. Create Android ViewStub programmatically in Kotlin

Open src/main/java/com.tutorialwing.dynamicviewstub/MainActivity.kt file. Then, add below code into it.

package com.tutorialwing.dynamicviewstub

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import android.widget.LinearLayout
import com.tutorialwing.dynamicviewstub.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() {
		val viewStub = ViewStub(this)
		val layoutParams = LinearLayout.LayoutParams(
			ViewGroup.LayoutParams.WRAP_CONTENT,
			ViewGroup.LayoutParams.WRAP_CONTENT
		)
		layoutParams.setMargins(40, 40, 40, 40)
		viewStub.layoutParams = layoutParams
		viewStub.layoutResource = R.layout.sub_item

		binding.rootContainer.addView(viewStub)

		viewStub.visibility = View.VISIBLE // or you can use viewStub.inflate()

		binding.btnShowHide.setOnClickListener {
			isViewInflated = !isViewInflated
			viewStub.visibility = if (isViewInflated) View.VISIBLE else View.GONE
			binding.btnShowHide.text =
				if (isViewInflated) getString(R.string.hide) else getString(R.string.show)
		}
	}
}

We have created viewStub programmatically in kotlin file (i.e. in MainActivity.kt file). Then, we have set layout params etc. in it. Attribute layoutResource is used to specify layout resource that replaces viewStub on inflate() method call. After that, we have added viewStub in linearLayout having id rootContainer. Finally, we have set click listener on button to toggle visibility of inflated view by viewStub.

Finally, when you run the application, you will get output as shown above.

Tutorialwing Kotlin Dynamic ViewStub Output Android ViewStub Programmatically in Kotlin Tutorial With Example

Tutorialwing Kotlin Dynamic ViewStub Output

Now, Let’s check how to use different attributes of ViewStub to customize it dynamically –

Set Id of ViewStub

Follow steps below to set id of ViewStub programmatically –

  • Create ids.xml file in res/values folder. Then, add below code into it –
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <item type="id" name="viewStub_ID" />
    </resources>
    
  • Now, we can set id of ViewStub dynamically, in MainActivity.kt file, as –

    viewStub.id = R.id.viewStub_ID  // ViewStub
    

    Here, we have set id of ViewStub using property access syntax – viewStub.id

Learn to Set ID of ViewStub Using XML Attribute

Set Width and Height of ViewStub

We use layoutParams to set width and height of any View programmatically. In this article, we have added ViewStub in LinearLayout. So, we will define LayoutParams as below –

viewStub.layoutParams = LinearLayout.LayoutParams(
	ViewGroup.LayoutParams.WRAP_CONTENT,
	ViewGroup.LayoutParams.WRAP_CONTENT
)

Here, we have set width and height as WRAP_CONTENT. Some of possible values for width and height are –

  • WRAP_CONTENT: Sets value of width or height depending on text inside it.
  • MATCH_PARENT: Sets value of width of height depending on width or height of parent layout . i.e. width or height of ViewStub will be same as width or height of parent layout.
  • Fixed Value: Sets width or height as per value provided.

Learn to Set Width or Height of ViewStub Using XML Attribute

Set Padding of ViewStub

Follow steps below to set padding of ViewStub Dynamically –

  • If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <dimen name="text_padding">16dp</dimen>
    </resources>
    
  • Now, we can set padding of ViewStub dynamically, in MainActivity.kt file, as –
    val padding = resources.getDimension(R.dimen.text_padding).toInt()
    viewStub.setPadding(padding, padding, padding, padding)
    

    Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, set padding of ViewStub using setPadding() method.

Learn to Set Padding of ViewStub Using XML Attribute

Set Margin of ViewStub

Follow steps below to set margin of ViewStub Dynamically –

  • If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <dimen name="text_margin">16dp</dimen>
    </resources>
    
  • Now, we can set margin of ViewStub dynamically, in MainActivity.kt file, as –
    val margin = resources.getDimension(R.dimen.text_margin).toInt()
    val layoutParams = LinearLayout.LayoutParams(
    	ViewGroup.LayoutParams.WRAP_CONTENT,
    	ViewGroup.LayoutParams.WRAP_CONTENT
    )
    layoutParams.setMargins(margin, margin, margin, margin)
    viewStub.layoutParams = layoutParams
    

    Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, we have defined layoutParams, set margin to layoutParams. After that, set layoutParams to ViewStub.

Learn to Set Margin of ViewStub Using XML Attribute

Set Background of ViewStub

Follow steps below to set background of ViewStub programmatically –

  • If there is no colors.xml file, create colors.xml file in res/values folder. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="purple_200">#FFBB86FC</color>
    </resources>
    
  • Now, we can set background of ViewStub dynamically, in MainActivity.kt file, as –
    val color = ContextCompat.getColor(this, R.color.purple_200)
    viewStub.setBackgroundColor(color)
    

    Here, we used setBackgroundColor() method to set background color in viewStub.

Learn to Set Background of ViewStub Using XML Attribute

Set Visibility of ViewStub

We can set visibility of ViewStub programmatically as –

viewStub.visibility = View.VISIBLE

Here, we have set visibility of ViewStub using viewStub.visibility attribute. Visibility can be of three types – gone, visible and invisible.
Learn to Set Visibility of ViewStub Using XML Attribute

That’s end of tutorial on ViewStub Programmatically in Kotlin With Example.

Leave a Reply