Can anyone explain or suggest a tutorial to dynamically create a ListView in android?
Here are my requirements:
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
, 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.