Java – how to dynamically add projects to listview in Android
•
Java
Who can help me? I'm trying to create a listview in Android, and I'm trying to load the project into it using code (not XML)
This is my code 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 on earth did I do wrong? These items are not displayed at run time
Editor: I changed the code according to the answer below. This is my current code
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 now get an exception
11-10 01:32:16.002: ERROR/AndroidRuntime(867): android.content.res.Resources$NotFoundException: Resource ID #0x7f050030 type #0x12 is not valid
Why can't I add them dynamically now?
Solution
You need to use the arrayadapter and add it to the listview Then simply add elements to the arrayadapter dynamically
For example:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1); tweetList.setAdapter(arrayAdapter); // ... arrayAdapter.add("New Item");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码