How to Add Views Dynamically and Store Data in Arraylist in Android?
Dynamic Views are created when we don’t want to have repeating XML code. In this article we will create a separate layout and inflate them inside a LinearLayout after that we will store the user data in an ArrayList as then display them as toast. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Step by Step Implementation
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language
Step 2: Add dependency inside build.gradle(app)
Add View Binding dependency inside the build.gradle(app) and click on the sync now button.
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. Notice that it has a Linear Layout with id parent_linear_layout which we will inflate to add our views.
Step 4: Create a new layout
Create a new layout named row_add_language.xml. This is the separate layout that we will inflate inside the Linear Layout with id parent_linear_layout.
Step 5: Add the entries item in string.xml that we have used in Spinner
Step 6: Create a new Kotlin class
Create a new Kotlin class Language.kt. This is the generic class which we will use for Arraylist to Store data.
Step 7: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Github repo here.