有谁能够帮我?我正在尝试在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();
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?这些项目未在运行时显示
编辑:我根据下面的答案更改了代码,这是我现在的代码
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();
Run Code Online (Sandbox Code Playgroud)
我现在得到一个例外
11-10 01:32:16.002: ERROR/AndroidRuntime(867): android.content.res.Resources$NotFoundException: Resource ID #0x7f050030 type #0x12 is not valid
Run Code Online (Sandbox Code Playgroud)
为什么我现在无法动态添加它们?
您需要使用ArrayAdapter并将其添加到ListView.然后只需ArrayAdapter动态添加元素.
例如:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
tweetList.setAdapter(arrayAdapter);
// ...
arrayAdapter.add("New Item");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11489 次 |
| 最近记录: |