【问题标题】:How can i inflate a listView dynamically in android [closed]我如何在android中动态地为listView充气[关闭]
【发布时间】:2012-04-22 11:22:26
【问题描述】:

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

提前致谢。

【问题讨论】:

标签: android listview


【解决方案1】:

扩展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>

【讨论】:

  • 非常感谢先生提供的代码......
猜你喜欢
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 2013-10-07
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多