0

please help me to create a list view dynamically and inflating it with some run time data.....

Thanks in advance.

Ashish Tamrakar
  • 810
  • 10
  • 24
  • You can find the samples [check here](http://wowjava.wordpress.com/2011/03/26/dynamic-listview-in-android/), [here](http://stackoverflow.com/questions/1917773/dynamic-listview-in-android-app) and [here](http://stackoverflow.com/questions/6938464/dynamically-add-items-in-list-view) – Abhi Apr 10 '12 at 06:45

1 Answers1

3

Extends ListActivity class and create object of ArrayList and use ArrayAdapter to add values.

public class ListViewDemo extends ListActivity {


//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();

//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;

//RECORDING HOW MUCH TIMES BUTTON WAS 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);
}

//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
 listItems.add("Clicked : "+clickCounter++);
 adapter.notifyDataSetChanged();
}
}

Also can be defined using layout xml,

Create a xml layout in your projects res/layout/main.xml folder

<?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>
Neetesh
  • 917
  • 1
  • 6
  • 16