[英]how do I add items to listview dynamically in android
有谁能够帮我? 我正在尝试在Android中创建一个ListView,我正在尝试使用代码(不使用XML)将项目加载到其中
这是我到目前为止的代码
tweetList = (ListView)this.findViewById(R.id.tweetListView);
TextView tv;
for(int i=0;i<20;i++)
{
tv = new TextView(this);
tv.setText("I'm a textView");
tweetList.addHeaderView(tv);
}
tweetList.invalidate();
我究竟做错了什么? 这些项目未在运行时显示
编辑:我根据下面的答案更改了代码,这是我现在的代码
tweetList = (ListView)this.findViewById(R.id.tweetListView);
ArrayAdapter<TextView> aa = new ArrayAdapter<TextView>(this, R.id.tweetListView);
tweetList.setAdapter(aa);
TextView tv;
for(int i=0;i<20;i++)
{
tv = new TextView(this);
tv.setText("I'm a textView");
//tweetList.addHeaderView(tv);
aa.add(tv);
}
tweetList.invalidate();
我现在得到一个例外
11-10 01:32:16.002: ERROR/AndroidRuntime(867): android.content.res.Resources$NotFoundException: Resource ID #0x7f050030 type #0x12 is not valid
为什么我现在无法动态添加它们?
您需要使用ArrayAdapter
并将其添加到ListView
。 然后只需动态地向ArrayAdapter
添加元素。
例如:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
tweetList.setAdapter(arrayAdapter);
// ...
arrayAdapter.add("New Item");
标题视图只是标题,而不是列表中的项目。 您的列表视图通过适配器接收其内容。 ListView
不为其子ListView
保留Views
,但是它的适配器创建它们并在需要在屏幕上显示时使用适当的数据填充它们。 搜索有关如何执行此操作的基本教程,有很多内容; 并记住适配器是关键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.