Open In App

How to Dynamically Add Elements to a ListView in Android?

Last Updated : 20 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

ListView is a UI widget in android which is used in most android applications. We can display the list of data using the list view. We can dynamically add or remove items from the list view by performing some operations of the list. In this article, we will take a look at How to add Elements to a ListView in Android Dynamically. A sample video is given below to get an idea about what we will do in this article.

Note: This Android article covered in both Java and Kotlin languages. 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Working with the activity_main.xml file

Navigate to app > res > layout > activity_main.xml and add the code below. Comments are added in the code to get to know in detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/idRLContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--on below line we are creating edit text
         for adding a new item to list-->
    <EditText
        android:id="@+id/idEdtItemName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:layout_toLeftOf="@id/idBtnAdd"
        android:hint="Enter item name to add in ist" />
 
    <!--button for adding item from edit text to list-->
    <Button
        android:id="@+id/idBtnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_margin="4dp"
        android:text="Add"
        android:textAllCaps="false" />
 
    <!--list view to display list of languages-->
    <ListView
        android:id="@+id/idLVLanguages"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/idEdtItemName" />
 
</RelativeLayout>


Step 3: Working with the MainActivity file 

Navigate to app > java > your app’s package name > MainActivity file and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating a variable.
    lateinit var languageLV: ListView
    lateinit var addBtn: Button
    lateinit var itemEdt: EditText
    lateinit var lngList: ArrayList<String>
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // on below line we are initializing our variables.
        languageLV = findViewById(R.id.idLVLanguages)
        addBtn = findViewById(R.id.idBtnAdd)
        itemEdt = findViewById(R.id.idEdtItemName)
        lngList = ArrayList()
 
        // on below line we are adding items to our list
        lngList.add("C++")
        lngList.add("Python")
 
        // on below line we are initializing adapter for our list view.
        val adapter: ArrayAdapter<String?> = ArrayAdapter<String?>(
            this@MainActivity,
            android.R.layout.simple_list_item_1,
            lngList as List<String?>
        )
 
        // on below line we are setting adapter for our list view.
        languageLV.adapter = adapter
 
        // on below line we are adding click listener for our button.
        addBtn.setOnClickListener {
           
            // on below line we are getting text from edit text
            val item = itemEdt.text.toString()
 
            // on below line we are checking if item is not empty
            if (item.isNotEmpty()) {
                // on below line we are adding item to our list.
                lngList.add(item)
 
                // on below line we are notifying adapter
                // that data in list is updated to update our list view.
                adapter.notifyDataSetChanged()
            }
        }
 
    }
}


Java




package com.gtappdevelopers.kotlingfgproject;
 
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
 
    // on below line we are creating variables.
    private ListView languageLV;
    private Button addBtn;
    private EditText itemEdt;
    private ArrayList<String> lngList;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // on below line we are initializing our variables.
        languageLV = findViewById(R.id.idLVLanguages);
        addBtn = findViewById(R.id.idBtnAdd);
        itemEdt = findViewById(R.id.idEdtItemName);
        lngList = new ArrayList<>();
 
        // on below line we are adding items to our list
        lngList.add("C++");
        lngList.add("Python");
 
        // on the below line we are initializing the adapter for our list view.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, lngList);
 
        // on below line we are setting adapter for our list view.
        languageLV.setAdapter(adapter);
 
        // on below line we are adding click listener for our button.
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // on below line we are getting text from edit text
                String item = itemEdt.getText().toString();
 
                // on below line we are checking if item is not empty
                if (!item.isEmpty()) {
 
                    // on below line we are adding item to our list.
                    lngList.add(item);
 
                    // on below line we are notifying adapter
                    // that data in list is updated to
                    // update our list view.
                    adapter.notifyDataSetChanged();
                }
 
            }
        });
    }
}


Now run your application to see the output of it. 

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads