Android ItemClickListener for a ListView with Images and Text

October 1, 2012
By

In this article we will create an Android application with a listview which holds both text and images as listview items. On clicking an item in the listview, corresponding country name will be displayed in a Toast Message.

This article is an extension to the article “ListView with Images and Text using Simple Adapter in Android

This application is developed in Eclipse ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 )


1. Create an Android application project namely “ListViewWithImagesAndTextClick”

Create a new Android Application Project

Figure 1 : Create a new Android Application Project


2. Design Application Launcher Icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank Activity to define the clas MainActivity

Create a blank Activity

Figure 3 : Create a blank Activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Delete Android’s Support Library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6.Create a directory namely “drawable” in the folder res/drawable


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


8.Open and Update the file res/values/strings.xml with the given below code


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="menu_settings">Settings</string>
    <string name="app_name">ListViewWithImagesAndTextItemClick</string>
    <string name="title_activity_main">ListViewWithImagesAndTextItemClick</string>
</resources>


9.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>


10. 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>


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


package in.wptrafficanalyzer.listviewwithimagesandtextclick;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

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

        // Item Click Listener for the listview
        OnItemClickListener itemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
                // Getting the Container Layout of the ListView
                LinearLayout linearLayoutParent = (LinearLayout) container;

                // Getting the inner Linear Layout
                LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);

                // Getting the Country TextView
                TextView tvCountry = (TextView) linearLayoutChild.getChildAt(0);

                Toast.makeText(getBaseContext(), tvCountry.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        };

        // Setting the item click listener for the listview
        listView.setOnItemClickListener(itemClickListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


12. Open and Update the file res/values/styles.xml


<resources>
    <style name="AppTheme" parent="android:Theme" />
</resources>


13. Open and Update the file res/values-v11/styles.xml


<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>


14. Open and Update the file res/values-v14/styles.xml


<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>


15. Run the application

Screenshot of the application in Action

Figure 5 : Screenshot of the application in Action


16. Download the source code


17. 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: , , ,

25 Responses to Android ItemClickListener for a ListView with Images and Text

  1. Amit on October 16, 2012 at 4:41 pm

    Hi,

    I have two images in one listView. i would like to launch two different intents on click of these images. How should I do it?

    • george on October 16, 2012 at 10:53 pm

      Hi Amit,
      You can do this by maintaining another array of intent details.

      • Varsha on January 14, 2015 at 10:01 am

        Sir, when i click on that listview , can i have intent based on imageview drawable?? I have tried but didn’t find a solution….Pls help me out….

        • George Mathew on January 14, 2015 at 3:52 pm

          Create the required intent in itemClickListener. This will work for you.

  2. JP on October 25, 2012 at 1:41 pm

    Hello, i’ve been trying your tutorial, all the items are showing fine, except that the OnItemClickListener is not working, i’ve put a simple Toast in it, even that isn’t showing…
    Here’s my code:

    ListView listCatCategories = (ListView) popupCatCategoriesView.findViewById(R.id.listCatCategories);
    List<HashMap> listCategories = new ArrayList<HashMap>();
    db.open();
    Cursor catCategories = db.getAllCatCategoryList();
    if (catCategories.moveToFirst())
    {
    do {
    HashMap hm = new HashMap();
    hm.put(“catCategoryThumbnail”, Integer.toString(catCategories.getInt(1)));
    hm.put(“catName”, catCategories.getString(0));
    listCategories.add(hm);
    } while (catCategories.moveToNext());
    }
    db.close();
    String [] from = { “catCategoryThumbnail”, “catName” };
    int[] to = { R.id.catCategoryThumbnail, R.id.txtCatCategoryName };
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), listCategories, R.layout.listview_cat_categories, from, to);
    listCatCategories.setAdapter(adapter);

    OnItemClickListener itemClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View container, int position, long id) {
    Toast.makeText(getBaseContext(), “item clicked”, Toast.LENGTH_SHORT).show();
    }
    };
    listCatCategories.setOnItemClickListener(itemClickListener);

    The variable popupCatCategoriesView is a view that i’ve inflated using LayoutInflator.
    Can you help? :-/

  3. undang on October 30, 2012 at 2:31 pm

    Thanks very much for your tutorial it very usefull for me..
    but how can i implement webview from every item when clicked ?
    please help me

  4. SM on November 9, 2012 at 12:39 pm

    Hi, my requirement is add checkbox in listview for each row and make it multiple choice enabled and once i check any items in list and click on one button placed outside of list , i should get all the checked items….plz help me on this…i m testing it in amdroid S2 emulator/device

  5. ravi on November 27, 2012 at 10:37 pm

    Hi can you show how to display image in full screen when the image in listview clicked

  6. Amit Bhaliya on July 4, 2013 at 7:54 pm

    Hello,
    This tutorial very nice but problem is that how to put hyperlink/url in this code please tell me.

    Thanking You
    Amit Bhaliya

  7. bhagya on August 31, 2013 at 5:54 pm

    Thanku,but u r using the local data,actually am using the url to externally it means RESTApi url how to parse the data.

  8. Adha dimas Liyanto on September 22, 2013 at 10:22 pm

    Sir i have a question it so hard to me
    in this point
    // 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
    };

    you said the image store in drawable.
    but i make it store in sqlite ,the type is BLOB . but i can not make list view like you .

    please sir help me ..
    i dont know what must i do .this problem has been 2weeks i still cant solve it..

  9. vikashini on December 30, 2014 at 11:39 pm

    hi
    Suppose i have a list of items in the list view with the image and text.
    on clicking of each item different activity should open for each item.how do i do that?please could you help me?

  10. geo on January 9, 2015 at 11:24 pm

    have a project on university application…which is found in Ethiopia…and my project name is Ethiopian University…which contains the whole information about each university…..i used a list view with images….i already append 25 items on a list with images….then what I want is when each item is clicked it should contain detail about the university(departments,background,MSC programs,PHD programs and contact information)…this is what I want …wheater textview or expandable list view……please help me …..thank you with regards

  11. Gokul on March 14, 2015 at 12:58 pm

    hi, i have a list view .in that when each item is clicked ,each one will have to a different page.how can i do that??

  12. Rameshwari on March 31, 2015 at 12:53 am

    Sir i tried ua code but m unable to c the image and the currency values.. the list only shows the country.. wht m i missin.. plzz help

  13. Divya on April 26, 2015 at 2:51 pm

    hi
    i actually wanted to know how to display a msg on other page, instead of a toast msg.. can u please tell me that

  14. TheBogueRat on May 30, 2015 at 7:21 am

    Thanks for your work on these tutorials. It helped me put together a menu for my app without all the mumbo jumbo that usually gets in the way. I was ready to give up until I found your blog. Thanks again!

  15. Adi on July 7, 2015 at 8:12 am

    hey, can i ask you something? ignore it if you not wish too.
    from what you have done above there, how can i make a new page?
    i mean, when i click the item example afganistan (from the program above) then it go to the new page. sorry my english is bad.

    my question is same with vikashini

  16. Maqsood on July 14, 2015 at 12:30 pm

    Sir, Instead of pop messages i want to set the descriptions how would i do that

  17. Ajish Nair on August 2, 2015 at 2:51 pm

    Hello Sir,

    I want to develop an android app of 500 songs lyrics. So pls tel me how to do it? it should work like this, when user click on songs 1, it should display the lyrics in another activity window. please guide me.
    Thanks in advance.

  18. tokuma yigezu on December 12, 2015 at 1:07 pm

    sir, i have one simple question. how to display many texts when i click on the lists above. for example,by clicking on country india,then getting some information about that country in another new page. thanks

  19. sagar on March 3, 2016 at 7:11 pm

    how to get toast only on image of listview
    i want to change image on click of image

  20. mansingh on June 11, 2016 at 1:00 am

    how add radio button in this addapter

  21. vinodh on July 28, 2016 at 7:31 pm

    sir, how can we pass selected items in recyclerview to another recycler in another activity. please help me …

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner