Add and Remove Views in Android Dynamically in Kotlin?

This example demonstrates how to Add and Remove Views in Android Dynamically in Kotlin.

Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.

Step 2  − Add the following code to res/layout/activity_main.xml.

Example



   
      
      
      
   
   

Step 3 − Add the following code to src/MainActivity.kt

Example

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   private var parentLinearLayout: LinearLayout? = null
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      parentLinearLayout = findViewById(R.id.parent_linear_layout)
   }
   fun onDelete(view: View) {
      parentLinearLayout!!.removeView(view.parent as View)
   }
   fun onAddField(view: View) {
      val inflater =
      getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
      val rowView: View = inflater.inflate(R.layout.field, null)
      parentLinearLayout!!.addView(rowView, parentLinearLayout!!.childCount - 1)
   }
}

Step 4 − Create a new Layout Resource file (field.xml) and add the following code −

Example


   
   
   

Step 5 − Open res/values/strings.xml and add the following code −

Example


YourAppName
   
      Mobile
      Office
      Home
   

Step 6 − Add the following code to androidManifest.xml

example



   
      
         
            
            
         
      
   

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Updated on: 2020-05-23T09:37:53+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements