如何在android中动态地扩展listView

时间:2012-04-10 06:36:43

标签: android listview

请帮我动态创建一个列表视图,并用一些运行时数据充实它......

提前致谢。

1 个答案:

答案 0 :(得分:3)

扩展ListActivity类并创建ArrayList的对象,并使用ArrayAdapter添加值。

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();
}
}

也可以使用layout xml,

来定义

在项目res / layout / main.xml文件夹中创建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>