How do I dynamically add elements in the Android list view?

Asked 2 years ago, Updated 2 years ago, 121 views

I need to make a list view. What you need now is that pressing the button dynamically adds new elements It's a code that's easy for me to understand without performance improvement or anything.

I know similar questions are already posted on this site, but it's a little different from exactly what I want. Help me.

android listview dynamic

2022-09-21 23:15

1 Answers

First, define xml. res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/addBtn"
        android:text="Add New Item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="addItems"/>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
    />
</LinearLayout>

This completes a simple layout with the button above and the list view below. Remember that the ID of the list view is @android:id/list. Used to define ListView in ListActivity.

public class ListViewDemo extends ListActivity {
    //Initialize elements to be listed 
    ArrayList<String> listItems=new ArrayList<String>();

    //Adapter declaration to handle data in the list 
    ArrayAdapter<String> adapter;

    //Variants that store how many clicks a button has been clicked 
    int clickCounter=0;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        adapter=new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,
            listItems);
        setListAdapter(adapter);
    }

    //Methods for dynamically adding elements to the list 
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }
}

Android.R.layout.simple_list_item_1 is the default list element layout provided by Android.

listItems is an array that stores elements in the list. If you want to add and delete elements in the list, you can add and delete elements in the listItems. And that processing in ArrayAdapter adapter

adapter.notifyDataSetChanged();Like this.

The adapter contains three items, one for Context, one for list item layout for listactivity, and one for actual data to show each item.

adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);


2022-09-21 23:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.