mattFllr
mattFllr

Reputation: 253

How to I add an image to list view items in Android?

I'm trying to add a different icon to each of my list items but I'm having trouble. The idea was to have each of the list view items together to make editing easier but adding an image is proving to be more complicated than I thought.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ArrayList<Map<String, String>> list = buildData();
    String[] from = { "title", "description" };
    int[] to = { android.R.id.text1, android.R.id.text2 };

    SimpleAdapter adapter = new SimpleAdapter(this, list,
            android.R.layout.simple_list_item_2, from, to);
    setListAdapter(adapter);
}

private ArrayList<Map<String, String>> buildData() {
    ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
    list.add(putData("Title 1", "Description 1"));
    list.add(putData("Title 2", "Description 2"));
    list.add(putData("Title 3", "Description 3"));
    return list;
}

private HashMap<String, String> putData(String name, String purpose) {
    HashMap<String, String> item = new HashMap<String, String>();
    item.put("name", name);
    item.put("purpose", purpose);
    return item;
}

Upvotes: 3

Views: 2272

Answers (3)

Jitsu
Jitsu

Reputation: 769

This is if not impossible, then at least quite troublesome at your current setup.

As the name states a SimpleAdapter is a basic class which provides you with basic functionality. That is, usually - a list with text views.

When you create the adapter you specify an exact layout for every single item in it (that's your android.R.layout_simple_list_item_2). You cannot push any additional items there (unless you're really stubborn).

What you need:

  • A custom made adapter (preferably)
  • A custom made layout for the adapter
  • A data source in the adapter which will map specific icons to every element.

Here is a nice demo: http://hmkcode.com/android-custom-listview-titles-icons-counter/

Upvotes: 1

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

Currently using simple_list_item_2.xml for ListView. this layout contains only two TextView's. so it's not possible to show image in ListView row's using simple_list_item_2.xml layout

How to I add an image to list view items in Android?

Should create a custom adapter :

1. Creating a custom layout with required views which want to show in each listview row like with TextView,ImageView,...

2. Create a custom adapter class by extending SimpleAdapter class to change behavior of getView method for showing images and textview from data-source

See following tutorial for reference :

ListView with Images and Text using Simple Adapter in Android

Upvotes: 0

KDeogharkar
KDeogharkar

Reputation: 10959

you can use custom adaptor in listview . so can customize your row. check this

Upvotes: 0

Related Questions