Android ListView example

In Android, ListView let you arranges components in a vertical scrollable list.

In this tutorial, we will show you 2 ListView examples :

  1. Normal way to display components in ListView.
  2. Custom array adapter to customize the item display in ListView.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Normal ListView example

In this example, we show you how to display a list of fruit name via ListView, it should be easy and self-explanatory.

1.1 Android Layout file

File : res/layout/list_fruit.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="20sp" >
</TextView>

1.2 ListView

package com.mkyong.android;
 
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
 
public class ListFruitActivity extends ListActivity {
 
	static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana",
			"Blueberry", "Coconut", "Durian", "Guava", "Kiwifruit",
			"Jackfruit", "Mango", "Olive", "Pear", "Sugar-apple" };
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
 
		// no more this
		// setContentView(R.layout.list_fruit);
 
		setListAdapter(new ArrayAdapter<String>(this, R.layout.list_fruit,FRUITS));
 
		ListView listView = getListView();
		listView.setTextFilterEnabled(true);
 
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			    // When clicked, show a toast with the TextView text
			    Toast.makeText(getApplicationContext(),
				((TextView) view).getText(), Toast.LENGTH_SHORT).show();
			}
		});
 
	}
 
}

1.3 Demo

android listview example

2. Custom ArrayAdapter example

In this example, we show you how to create 4 items in the ListView, and use a custom “ArrayAdapter” to display different images base on the “item name” in the list.

2.1 Images
Get 4 images for demonstration.

images in android project

2.2 Android Layout file
File : res/layout/list_mobile.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >
 
    <ImageView
        android:id="@+id/logo"
        android:layout_width="50px"
        android:layout_height="50px"
        android:layout_marginLeft="5px"
        android:layout_marginRight="20px"
        android:layout_marginTop="5px"
        android:src="@drawable/windowsmobile_logo" >
    </ImageView>
 
    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:textSize="30px" >
    </TextView>
 
</LinearLayout>

2.3 Custom ArrayAdapter
Create a class extends ArrayAdapter and customize the item display in the getView() method.

package com.mkyong.android.adaptor;
 
import com.mkyong.android.R;
 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
 
public class MobileArrayAdapter extends ArrayAdapter<String> {
	private final Context context;
	private final String[] values;
 
	public MobileArrayAdapter(Context context, String[] values) {
		super(context, R.layout.list_mobile, values);
		this.context = context;
		this.values = values;
	}
 
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
			.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
		View rowView = inflater.inflate(R.layout.list_mobile, parent, false);
		TextView textView = (TextView) rowView.findViewById(R.id.label);
		ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
		textView.setText(values[position]);
 
		// Change icon based on name
		String s = values[position];
 
		System.out.println(s);
 
		if (s.equals("WindowsMobile")) {
			imageView.setImageResource(R.drawable.windowsmobile_logo);
		} else if (s.equals("iOS")) {
			imageView.setImageResource(R.drawable.ios_logo);
		} else if (s.equals("Blackberry")) {
			imageView.setImageResource(R.drawable.blackberry_logo);
		} else {
			imageView.setImageResource(R.drawable.android_logo);
		}
 
		return rowView;
	}
}

2.4 ListView
ListView, but use above custom adapter to display the list.

package com.mkyong.android;
 
import com.mkyong.android.adaptor.MobileArrayAdapter;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import android.view.View;
 
public class ListMobileActivity extends ListActivity {
 
	static final String[] MOBILE_OS = 
               new String[] { "Android", "iOS", "WindowsMobile", "Blackberry"};
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
 
		setListAdapter(new MobileArrayAdapter(this, MOBILE_OS));
 
	}
 
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
 
		//get selected items
		String selectedValue = (String) getListAdapter().getItem(position);
		Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
 
	}
 
}

2.5 Demo

android custom array adapter example

Download Source Code

Download both examples – Android-ListView-Example.zip (21 KB)

References

  1. Android ListView example
  2. Android ListView JavaDoc
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Bob

    Thanks in advance!

    Can you please tell me how to set clicklistener to each listview item? I want mij each item to nagivate to different pages.

    Right now I wrote the following code that all items go to the same page:

    list.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView arg0, View arg1, int position,
    long arg3) {
    startActivity(new Intent(Participant.this,Contact.class));
    }
    });

  • Pingback: How to create Expandable Forms? | BlogoSfera()

  • Pingback: How to create Expandable Forms?CopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nodejsquery, dns query, update query, inse()

  • Mack

    Hi, nice tutorial!
    Can you please explain, how to change to color of some rows of the listview?
    I can change the color of the whole listview, but I don’t know how change
    the color of a specified row.
    I want to have several blocks in my listview.
    Every block has an integer ID.
    The row between two blocks should have another color (like a separator).
    Could you please help?
    Thanks!

  • avnish

    sir, I have spinner that bind with custom ArrayAdapter (id,name).
    i want to set spinner position with id and display name in spinner(id is hidden).

  • reza

    thanks very much mkyong
    your web is very good and helped me

  • sai

    at last I got it right… the mistake was in manifest.xml

    thank you mkyoung

  • Michael

    After successfully running the code I get “Unfortunately, the app has stopped”. Any solutions or helpful information to help me solve this?

    • sai

      View rowView = convertView;
      if (rowView == null) {
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      rowView = inflater.inflate(R.layout.item_menu, parent, false);
      }

      use this code in custom listview

  • sai

    no errors are there but the code is not running…

    what I have to change.. help me??

  • sai

    package com.holy.goly;

    import com.listview.lively.MainActivity;
    import android.app.ListActivity;
    import android.os.Bundle;
    import android.widget.ListView;
    import android.widget.Toast;
    import android.view.View;
    public class Lone extends ListActivity {

    static final String[] MOBILE_OS =
    new String[] { “Android”, “iOS”, “WindowsMobile”, “Blackberry”};

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setListAdapter(new MainActivity(this, MOBILE_OS));

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

    //get selected items
    String selectedValue = (String) getListAdapter().getItem(position);
    Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();

    }

    }

  • sai

    package com.listview.lively;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;

    public class MainActivity extends ArrayAdapter {
    private final Context context;
    private final String[] values;

    public MainActivity(Context context, String[] values) {
    super(context, R.layout.activity_main, values);
    this.context = context;
    this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = convertView;
    if (rowView == null) {
    inflater = (LayoutInflater)
    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    rowView = inflater.inflate(R.layout.activity_main, parent, false);
    }

    rowView = inflater.inflate(R.layout.activity_main, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
    textView.setText(values[position]);

    // Change icon based on name
    String s = values[position];

    System.out.println(s);

    if (s.equals(“WindowsMobile”)) {
    imageView.setImageResource(R.drawable.b);
    } else if (s.equals(“iOS”)) {
    imageView.setImageResource(R.drawable.c);
    } else if (s.equals(“Blackberry”)) {
    imageView.setImageResource(R.drawable.d);
    } else {
    imageView.setImageResource(R.drawable.e);
    }

    return rowView;
    }
    }

  • http://google sakthi

    i want listview program

  • http://google sakthi

    package com.example.mygame;

    import com.example.mygame.R.id;
    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.AdapterView.OnItemClickListener;
    public class SecondActivity extends ListActivity implements OnClickListener
    {

    Button b3, shake;
    /*ListView listview;
    static final String[] numbers = new String[] {
    “one”, “two”, “three”, “four”, “five”,
    “six”, “seven”, “eight”, “nine”, “ten”,
    “eleven”, “twelve”, “thirteen”, “fourteen”,
    “fifteen”,”sixteen”,”seventeen”,”eighteen”,
    “nineteen”,”twenty”,”twenty one”,”twenty two”
    };*/
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    b3=(Button)findViewById(R.id.button3);
    shake=(Button)findViewById(R.id.button7);
    b3.setOnClickListener(this);
    shake.setOnClickListener(this);
    /*listview = (ListView) findViewById(R.id.action_settings);
    ArrayAdapter adapter = new ArrayAdapter
    (this,android.R.layout.simple_list_item_1, numbers);

    listview.setAdapter(adapter);
    listview.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView parent, View v,
    int position, long id) {
    Toast.makeText(getApplicationContext(),
    ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
    }
    });
    */
    }
    public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button3:
    Intent Home= new Intent(SecondActivity.this,FirstActivity.class);
    startActivity(Home);

    break;
    case R.id.button7:
    Intent shake= new Intent(SecondActivity.this,ThirdActivity.class);
    startActivity(shake);
    break;
    default:
    break;
    }

    }

    }
    i develop this program but i cant open the list view if you have answer reply me

  • faeze_el

    tnx alot

  • Nima Ahmadi

    hey! nice job!
    but you should check the convertView before making a new rowView.

    • http://romainpellerin.eu/ Romain

      Nima Ahmadi you’re right. Here is the modified code:

      View rowView = convertView;
      if (rowView == null) {
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      rowView = inflater.inflate(R.layout.item_menu, parent, false);
      }

      • sai

        where to insert this code exactly??

      • sai

        I am new to android,this code is not running can some one help me…?

  • http://romainpellerin.eu Romain

    THANK YOU SO MUCH! I’ve been looking for an easy tutorial like yours for a while!! Thank you dude! Good job!

  • http://www.paketwisatamurah.net paket wisata murah

    nice coding, i likes

  • Jane

    THANK YOU

  • http://skylite.com Raheel

    Hello There I have creat a ListView just like you listView but I want to set Onclicklistner listView can you Tell me how can I do that.?

  • Abdelrahman

    How to make this list Fill The Screen, Make all subItems bigger enought to fill the screen as if I gave each one Equal Weight

  • Pingback: Add arraylist to listfragment : Android Community - For Application Development()

  • Jayanth

    Thank you for the simple yet useful tutorial

  • Pingback: how to open an new screen from a listview : Android Community - For Application Development()

  • http://pavanhd.blogspot.in/ pavan

    How to include a list under a list
    i mean sublisting

  • Pingback: Notes from building an Android app | Shining Leaf()

  • koko

    thank for this helpful tutorial.
    how do i set a the setOnItemClickListener method in order to open a new activity.
    regards

  • http://android.programmerguru.com Android Guru

    How to check whether Wi-Fi internet access is active or not in a device. Take a look at the post:
    http://android.programmerguru.com/android-check-wifi-internet-connection/

  • okfriansyah

    Hey how to use that list on listfragment. i already make list with same icon in list fragment. but how to make different icon in listfragment?

  • Pingback: Android:ListView and events each item : Android Community - For Application Development()

  • Pingback: List View Error in Android : Android Community - For Application Development()

  • Michael Cohen

    Thanks. Nice job!

  • Abilash

    Thanks

  • islealoha

    In the “res/layout/list_fruit.xml” file, the “TextView” widget has no “Layout” wrapper around it. Can someone explain why. It doesn’t work when I tried to add a “Layout” wrapper around it and try to add a button or other widgets.

    I don’t understand how the “TextView” widget gets turned into a “ListView” widget by the “ListFruitActivity.JAVA” activity. Can someone explain how all these magic potions work together and how can I modify the XML to add another WIDGET without using “Adapter”? Still very confusing. Thank you.

  • islealoha

    In the “res/layout/list_fruit.xml” file, the widget has no wrapper around it. Can someone explain why. It doesn’t work when I tried to add a wrapper around it to add a button or other widgets.

    I don’t understand how the becomes a from the ListFruitActivity.JAVA activity. Can someone explain how all these magic potions work together and how to change the XML to add another WIDGET? Still very confusing. Thank you.

  • http://www.poropopo.com David

    Hi, how i put a multiple listviews in one activity(layout) Example:
    —————————–(Inicio pantalla)
    | List1
    | DATA1
    | DATA2
    |……
    | List2
    | DATA1
    | DATA2
    |……
    | List3
    | DATA1
    ————————(Fin de pantalla)
    | DATA2
    |……
    | List4
    | DATA1
    |……

    • User0

      Use a Hashmap or custom Bean Class instead of a String[]

      extends ArrayAdapter&lt;MyClass&gt;

      etc.
      also, try filling images a cleaner way, little example:

      String uri = MyClass.getImagePath(); //something like drawable/image
      Drawable image = context.getResources().getDrawable(context.getResources().getIdentifier(uri, null, context.getPackageName()));
  • Pingback: Cannot retrieve data from database and add it to list : Android Community - For Application Development()

  • Pingback: Creating Listview dynamically in Android : Android Community - For Application Development()

  • Pingback: Two columns for ListView or TableLayout in Landscape mode : Android Community - For Application Development()

  • http://www.googgle.com.pe/ Ssldke Malske

    Note

    To post source code in comment, uses

     

    tag, for examples :

     Java source code here
     XML here
  • http://www.googgle.com.pe/ Ssldke Malske

    majde ndjh lsjkeio

     
     Java source code here
     XML here
  • http://www.grosiraksesoriswanita.net Aina

    thank you very much , can you tell me where I can get tutorial to start new activity from list view?

  • akki

    hi i just want to know what is epub reader could u explain it briefly if possible for u is it done on androi or ios aplication could u provide solution for my problem

  • Rich Mayo

    Where is your software getting your list titles? I can’t find “List of Fruits” or “List of Mobile OS” anywhere.

  • Pingback: How to make a list in an android app? : Android Community - For Application Development()

  • Pingback: Android Listview Position | Apps For Mobile()

  • Pingback: Fetching data from intent causes app to crash : Android Community - For Application Development()

  • Pingback: Fetching data from intent causes app to crash video()