How do you dynamically add elements to a ListView on Android?

后端 未结 7 2043
情歌与酒
情歌与酒 2020-11-22 08:47

Can anyone explain or suggest a tutorial to dynamically create a ListView in android?

Here are my requirements:

  • I should be able to dynamically add new e
7条回答
  •  死守一世寂寞
    2020-11-22 09:43

    Create an XML layout first in your project's res/layout/main.xml folder:

    
    
        

    This is a simple layout with a button on the top and a list view on the bottom. Note that the ListView has the id @android:id/list which defines the default ListView a ListActivity can use.

    public class ListViewDemo extends ListActivity {
        //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
        ArrayList listItems=new ArrayList();
    
        //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
        ArrayAdapter adapter;
    
        //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
        int clickCounter=0;
    
        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);
            adapter=new ArrayAdapter(this,
                android.R.layout.simple_list_item_1,
                listItems);
            setListAdapter(adapter);
        }
    
        //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
        public void addItems(View v) {
            listItems.add("Clicked : "+clickCounter++);
            adapter.notifyDataSetChanged();
        }
    }
    

    android.R.layout.simple_list_item_1 is the default list item layout supplied by Android, and you can use this stock layout for non-complex things.

    listItems is a List which holds the data shown in the ListView. All the insertion and removal should be done on listItems; the changes in listItems should be reflected in the view. That's handled by ArrayAdapter adapter, which should be notified using:

    adapter.notifyDataSetChanged();

    An Adapter is instantiated with 3 parameters: the context, which could be your activity/listactivity; the layout of your individual list item; and lastly, the list, which is the actual data to be displayed in the list.

提交回复
热议问题