Add List Item in ListView Android Example

Sample Code to Add List items Dynamically in ListView Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/RelativeView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    >

    <Button
        android:id="@+id/AddItemBtn"
        android:layout_width="374dp"
        android:layout_height="wrap_content"
        android:text="Add Items In ListView" />

    <ListView
        android:id="@+id/ListViewID"
        android:layout_width="wrap_content"
        android:layout_height="501dp"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>

 

MainActivity.class

package com.freakyjolly.addlistitemdynamic;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get reference of widgets from XML layout
        final ListView ListView = (ListView) findViewById(R.id.ListViewID);
        final Button AddItem = (Button) findViewById(R.id.AddItemBtn);

        // Initializing a new String Array
        String[] fruits = new String[] {
                "Item 1",
                "Item 2"
        };

        // Create a List from String Array elements
        final List<String> fruits_list = new ArrayList<String>(Arrays.asList(fruits));

        // Create an ArrayAdapter from List
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
                (this, android.R.layout.simple_list_item_1, fruits_list);

        // DataBind ListView with items from ArrayAdapter
        ListView.setAdapter(arrayAdapter);

        AddItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Add new Items to List
                fruits_list.add("Freaky");
                fruits_list.add("Jolly");
                /*
                    notifyDataSetChanged ()
                        Notifies the attached observers that the underlying
                        data has been changed and any View reflecting the
                        data set should refresh itself.
                 */
                arrayAdapter.notifyDataSetChanged();
            }
        });
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *