我如何将项目添加到Android中的ListView动态 [英] how do I add items to listview dynamically in android

查看:140
本文介绍了我如何将项目添加到Android中的ListView动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能帮助我吗?我试图创建Android的一个ListView,我试图用项加载到其中code(不使用XML)

Can anybody help me? I'm trying to create a ListView in Android, and I'm trying to load items into it using code (not using XML)

这里的code,我至今

Here's the code that I have so far

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

我是什么做错了吗?该项目未在运行时显示

What am I doing wrong? The items are not showing in runtime

编辑:我改变了code按下面的答案,这里的code现在我有

I changed the code as per the answers below and here's the code I have now

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

我现在得到一个例外

I'm getting an exception now

11-10 01:32:16.002: ERROR/AndroidRuntime(867): android.content.res.Resources$NotFoundException: Resource ID #0x7f050030 type #0x12 is not valid

为什么我无法将它们添加动态呢?

Why am I not able to add them dynamically now?

推荐答案

您需要使用 ArrayAdapter ,并把它添加到的ListView 。然后,只需添加元素到 ArrayAdapter 动态。

You need to use ArrayAdapter and add it to the ListView. Then just add elements to the ArrayAdapter dynamically.

例如:

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
tweetList.setAdapter(arrayAdapter);
// ...
arrayAdapter.add("New Item");

这篇关于我如何将项目添加到Android中的ListView动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆