Jake Wilson
Jake Wilson

Reputation: 91233

Android - Dynamically add items to ListView using existing XML layouts?

I have a ListView that I want to dynamically add items to. For the items, I want to use a specific layout that I have defined in XML. How do I go about adding the items to it and have each item use the specific XML layout?

Do I have to create an adapter and jump through all those hoops? There is only a handful of items that I need to display. Each item has a few text views that need to be populated as well as an image that needs to be displayed.

If I go with the Adapter route, I need to basically creating a custom object/class that contains the text for each textview as well as the URL of the image I'm downloading. Seems like way overkill for just displaying a handful of listview items.

Isn't there someway I can just iterate through my items, inflate a view for each and add them to the listview?

Upvotes: 0

Views: 2246

Answers (3)

kabuko
kabuko

Reputation: 36312

Either you can create an adapter which is really not all that complicated, or you can use a ScrollView with a LinearLayout inside and inflate yourself. Either option is reasonable, depending on your requirements, but inflating yourself and adding the views to the ListView manually isn't one of them. By the description you give, it sounds like you might just want to go the LinearLayout route.

  • Put a ScrollView with a LinearLayout inside in your main layout XML.
  • For each child:
    • Inflate the view for the child item and populate the fields accordingly.
    • Add the child view to the LinearLayout using addView.

Upvotes: 0

josephus
josephus

Reputation: 8304

you want to use a ScrollView for your purpose. works just like a listview, except the rule is a ScrollView should only have one child layout (that layout would be containing all the items you want to put inside). inflate a layout, then addView(). rinse repeat.

Upvotes: 2

Damian
Damian

Reputation: 8072

Unfortunately you do have to create an adapter. SimpleAdapter is about as easy as it gets. Here's a nice example that'll have you up and running in a few mins:

http://ykyuen.wordpress.com/2010/01/03/android-simple-listview-using-simpleadapter/

Upvotes: 0

Related Questions