ListView with Images and Text using Simple Adapter in Android

June 18, 2012
By

In this article we will create an android application with a listview which holds both text and images as listview items.



An extension to this article is available in the article titled “Android ItemClickListener for a ListView with Images and Text“, where an item click event handler is added.

For loading images and text from Internet , see the article titled “Android Lazy Loading images and text in listview from http json data“.



1. Create an Android project namely “ListViewWithImagesAndText”

ListViewWithImagesAndText : New Android Project

Figure 1: Create new Android Project


2. Select build target

Select Build Target

Figure 2: Select Build Target


3. Enter application details

Application Details

Figure 3: Application Details


4. Download and extract the zip file containing flag’s images to the directory /res/drawable-ldpi


5. Open and update the file /res/layout/main.xml with the given below code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
</LinearLayout>

6. Create a new file namely /res/layout/listview_layout.xml  and update the content with the given below code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
>
    <ImageView
        android:id="@+id/flag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/hello"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
    />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
    >
        <TextView
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15dp"
        />

        <TextView
            android:id="@+id/cur"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10dp"
        />
    </LinearLayout>
</LinearLayout>

7. Open and update the file /src/in/wptrafficanalyzer/listviewwithimagesandtext/MainActivity.java with the given below code


package in.wptrafficanalyzer.listviewwithimagesandtext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

    // Array of strings storing country names
    String[] countries = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan"
    };

    // Array of integers points to images stored in /res/drawable-ldpi/
    int[] flags = new int[]{
        R.drawable.india,
        R.drawable.pakistan,
        R.drawable.srilanka,
        R.drawable.china,
        R.drawable.bangladesh,
        R.drawable.nepal,
        R.drawable.afghanistan,
        R.drawable.nkorea,
        R.drawable.skorea,
        R.drawable.japan
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
        "Indian Rupee",
        "Pakistani Rupee",
        "Sri Lankan Rupee",
        "Renminbi",
        "Bangladeshi Taka",
        "Nepalese Rupee",
        "Afghani",
        "North Korean Won",
        "South Korean Won",
        "Japanese Yen"
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Each row in the list stores country name, currency and flag
        List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

        for(int i=0;i<10;i++){
            HashMap<String, String> hm = new HashMap<String,String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur","Currency : " + currency[i]);
            hm.put("flag", Integer.toString(flags[i]) );
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = { "flag","txt","cur" };

        // Ids of views in listview_layout
        int[] to = { R.id.flag,R.id.txt,R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);

        // Getting a reference to listview of main.xml layout file
        ListView listView = ( ListView ) findViewById(R.id.listview);

        // Setting the adapter to the listView
        listView.setAdapter(adapter);
    }
}


8. Run the application

Application in Execution

Figure 4: Application in Execution


9. Download the source code


10. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

53 Responses to ListView with Images and Text using Simple Adapter in Android

  1. John on September 3, 2012 at 11:37 pm

    Hello, this is a very good example, but how could I do it if the images are not resources in the project?? I mean like a Bitmap or something.

    Thanks.

    • george on September 5, 2012 at 11:49 am
      • John on September 5, 2012 at 10:42 pm

        Hello, and what if I want to show some pictures I have downloaded from internet and are stored in a list?

        I’m trying to show some news downloaded from a rss source and every news contains a picture, and I would like to show it, but no results until now, only text is shown.

        How could I do it??

        • John on September 6, 2012 at 2:28 am

          Never mind, I got it. ;-P

          • Dan on December 16, 2013 at 8:51 pm

            Hi John, could you let me know how you did it?

            Thanks

    • Muhammad Ifthikhar on February 15, 2015 at 5:12 pm

      Wonderful tutorial.
      Thanks

  2. udi on September 7, 2012 at 6:31 pm

    very helpfull!
    thanks you very much

  3. André on September 10, 2012 at 8:14 pm

    Great tutorial! By far the easiest one to understand. Thanks!

  4. Android Rao on September 12, 2012 at 12:24 pm

    This is great tutorial, ss there any further enhancement to this utility on when list item click?

    Thanks.

  5. Dexter on September 26, 2012 at 10:34 pm

    Excellent tutorial for beginners

  6. Arief Rivai on September 30, 2012 at 7:22 pm

    Wow.. Thanks for great tutorial..
    But how to implement OnClickListener in this code? I tired to try :( I hope u help me.. Thanks@

  7. ines on October 8, 2012 at 5:15 am

    great tutorial but how can i display pictures coming from server (located in a folder) and just their id whitch are saved in a database mysql???
    I want find out how can i use a web service for creating a table sqlite in android to synchronize with the table mysql and display with her all my pictures!!!!!!
    HELP ME PLEASE !!

  8. Ashish on November 13, 2012 at 1:45 pm

    very helpful…for me

  9. Friend from VietNam on November 17, 2012 at 8:11 pm

    Thank for your tutorial. it realy good example for custom listview. But I have a problem. When I get information from SQLite via Cursor, and send it to arraylist. With “country” and “currency” list, I can do it, but “flag” is can’t. In my roject I custom it like “image Avatar”, “Name”and “type”. Type maybe is: bar, coffee or restaurant. If type is bar, image Avatar will be show “bottle of beer”, and if is coffee, it show “coffee cup”, like this for bar.
    So, how I can do it? Please help me.
    .
    Hieu Nguyen Trung

  10. Monisha on November 18, 2012 at 7:12 pm

    Thank you George…. It helped for me…

  11. Gui on January 1, 2013 at 11:47 pm

    Thanks for this tutorial, it helps a lot.

    I thought it wasn’t possible to use a simpleAdapter with images because of the following text in the documentation:

    constructor parameters:
    to [...] These should all be TextViews. [...]

    Where’s the magic? Is it a mistake in the documentation?

  12. kalpesh patel on January 25, 2013 at 12:28 pm

    how can we add two or more images in listview???

  13. androtition on February 4, 2013 at 4:23 pm

    Great tutorial, Now If want to delete some particular row then how’s that possible??

  14. Prakash Gavade on March 24, 2013 at 5:09 pm

    Great Tutorial helps me lot….Thank You very much….

  15. Sergey Danilov on March 28, 2013 at 6:03 pm

    Very good lesson!!! The large thank.
    Hi from Russia.

  16. man on April 30, 2013 at 4:39 pm

    Really helpfull tutorial. Thank you very much.

  17. Ricardo on May 9, 2013 at 3:47 am

    First things first: thanks for this great tutorial!

    Second: I have adapted the code for my android app, but I am faced with a small problem: text gets cut off, since the text string is variable. Would know how to solve this problem? Or point me in the rigth direction (web content, etc… xD)?

    Cheers from Portugal
    Ricardo

  18. Ricardo on May 9, 2013 at 4:20 am

    I forgot to add:

    In listview_layout.xml, if i change the orientation i get the following results:

    android:orientation=”vertical” image is displayed over the text, but text is presented correctly (without being cut off).

    android:orientation=”horizontal” image is displayed to the left of the text, but text is presented incorrectly (cut off).

    The goal is to the image to be displayed to the left without getting cut off xD

  19. Tachikoma on May 15, 2013 at 3:46 am

    Thanks, this is a straight forward example.

  20. Triston on May 23, 2013 at 10:38 pm

    WOW thank you SOOOO much for the lesson
    Best and easiest way to get images and text into listview
    Best of luck for your future
    T

    • Triston on May 23, 2013 at 10:38 pm

      Best Ever

  21. sanjay on June 7, 2013 at 12:55 pm

    Hi george i want know how can i show different different text along with country information at bottom of imageview whenever clicked by any user and also i want know i have take imagebutton on right of text view and i want call new activity how can i do plz let me know reply soon…………..

  22. Niju on June 15, 2013 at 10:23 am

    Hey your code worked properly.Next thing I want to know is to how to put the strings below the images,I want to display the list view as an image and the text as up and down.pls reply….

  23. Miiro Bels on June 26, 2013 at 1:21 pm

    how do you implement selected item like i want to select china. how do u implement that coz i have faile

  24. Jorari71 on July 14, 2013 at 3:38 am

    Hi!.

    I was trying to add 2 buttons per row/item in my ListView taking your example as base and I don’t know why I click/tap on the buttons I’ve added and they don’t give me any result (Showing my println ). Any idea?. Here’s my code:

    if (convertView == null) {
    holder = new ViewHolder();
    convertView = mInflater.inflate(R.layout.list_item, null);
    .
    .
    .
    holder.menos = (Button)convertView.findViewById(R.id.buttonmenos);
    holder.mas = (Button)convertView.findViewById(R.id.buttonmas);
    .
    .
    .
    convertView.setTag(holder);
    else{
    holder = (ViewHolder) convertView.getTag();
    }
    }

    holder.menos.setOnClickListener(new Button.OnClickListener()
    {
    public void onClick(View v)
    {
    System.out.println(“inside the buttonlistener1!!”);
    }
    });

    holder.mas.setOnClickListener(new Button.OnClickListener()
    {
    public void onClick(View v)
    {
    System.out.println(“inside the buttonlistener2!!”);
    }
    });

    class ViewHolder {
    Button mas;
    Button menos;
    int position;
    }
    class ListItem {
    String caption;
    Integer images;

    }
    }

  25. vqojopv on April 27, 2014 at 3:31 am

    The php code:
    $row['countryname'],
    ‘flag’ => $row['flag'],
    ‘language’ => $row['language'],
    ‘capital’ => $row['capital'],
    ‘currency’ => array(
    ‘code’ => $row['code'],
    ‘currencyname’ => $row['currencyname']
    )
    )
    );
    }
    mysqli_free_result($sql);

    header(‘Content-type: application/json’);
    echo json_encode($currency);
    ?>

  26. LeeTH on September 2, 2014 at 12:39 pm

    How good and simple example of ListView with image and text.

    Thank you so much for this wonderful example.

  27. navya on September 10, 2014 at 5:54 pm

    Hey Nice Tutorial,
    Can you tell me how to add different colors as background for each flag?

    Thanks

  28. Jafeena Thaha on November 21, 2014 at 4:07 pm

    Very good tutorial. Worked properly. Thank You.

  29. Umair on December 7, 2014 at 11:19 pm

    bro i have path of pics ..i want to retrive those pics from sd-card folder …and show them on listview …how to do that ..i dont have pics in drawable ..:( plzplz help bro

  30. saikiran on December 18, 2014 at 12:29 pm

    The tutorial is good,But if i click the listtextitem in listView,it must highlight permanently and if i click another text item,the previous item which is clicked must be faded and this clicked text item must be highlighted…

  31. selva on December 27, 2014 at 3:01 pm

    Hey your code worked.while I tried to update the values of adapter getting error.can you help me………

  32. lata on March 3, 2015 at 10:38 am

    i want code for spinner in custom listview plz help me

  33. mohamed hanifa m on March 23, 2015 at 9:33 pm

    how to upload image and text via admin app using php then download by custom list view.
    could u explain with including php code

  34. SundaraManikandan on March 26, 2015 at 7:29 pm

    Hi, how to add buttons in each listview row?

    • Tanya on April 21, 2015 at 4:29 pm

      You can Simply add button in the XML layout.
      But Its nothing more then a show.
      As we are not able to perform any selection operation neither on Listview, Image, Text nor on Buttons.

      So In case you get the solution please let me know.

      • Intan on May 6, 2016 at 9:59 pm

        Hi..do you get the solution yet? im stuck..help me please..

      • Intan on May 7, 2016 at 9:35 am

        hi..do you get the solution yet? please let me know..im stuck

  35. Diego on August 26, 2015 at 10:11 am

    Wonderful, pretty clear.

  36. Aditi on February 12, 2016 at 1:10 pm

    how to take different images and different text in one row by adding list view

    plzzz help me

    • Aditi on February 12, 2016 at 1:12 pm

      in xml i have to design plzzz answer me as soon as.

  37. vinodh on March 15, 2016 at 7:34 pm

    wonderful. can we load the list view from the my sql by using php!!!!!!!

  38. vinodh on March 18, 2016 at 12:51 pm

    your tutorial is very helpful to me. if we image and text taken from mysql database using php in list view. how can we implement???? plz help me sir….

  39. mansingh on June 11, 2016 at 3:13 am

    can posible add radio button single in this code

  40. mansingh on June 12, 2016 at 4:23 pm

    how add radio button in this example

  41. rajitha on July 4, 2016 at 6:02 pm

    Hi,
    Thanks for the tutorial.
    I need help in fetching the image from te mysql database to andoid.I have stored the image in database with the file name of image like flower_veg.jpg.I am not able to fetch the image.Kindly help me in this.

Leave a Reply to Jafeena Thaha Cancel reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner