Você está na página 1de 16

Android ListView example Advertise Contact Us Write For Us Java Forum RSS feed

Home All Tutorials Java Core Java Core Tutorials

1. Java I/O 2. Java XML 3. Java JSON 4. Java RegEx 5. JDBC 6. Java Misc JSF JSF Tutorials

1. JSF 2.0 Spring Spring Tutorials

1. Spring Core 2. Spring MVC 3. Spring Security Hibernate Hibernate Tutorials

1. Hibernate Core Struts Struts Tutorials

1. Struts 1 2. Struts 2 Android Android Tutorials

1. Android Core Others Apache Wicket JAX-WS (SOAP) JAX-RS (REST) Maven Google App Engine Java MongoDB jUnit TestNG jQuery Quartz Scheduler

Android ListView example

Posted on January 12, 2012 , By mkyong

Last modified : August 29, 2012

In Android, ListView let you arranges components in a vertical scrollable list. In this tutorial, we will show you 2 ListView examples : Normal way to display components in ListView. 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 import import import import import import import import android.app.ListActivity; android.os.Bundle; android.view.View; android.widget.AdapterView; android.widget.ArrayAdapter; android.widget.ListView; android.widget.TextView; android.widget.Toast; android.widget.AdapterView.OnItemClickListener;

public class ListFruitActivity extends ListActivity { static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banan a", "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_frui t,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

<!-- google_ad_client = "pub-2836379775501347"; /* 728x90, created 11/18/07 */ google_ad_slot = "7391621200"; google_ad_width = 728; google_ad_height = 90; google_ad_region = "mkyongregion"; //--> 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.

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 import import import import import import android.content.Context; android.view.LayoutInflater; android.view.View; android.view.ViewGroup; android.widget.ArrayAdapter; android.widget.ImageView; 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, fa lse); 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(positio n); Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show(); } } 2.5 Demo

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

References Android ListView example Android ListView JavaDoc Tags : androidlistview <!-- google_ad_client = "ca-pub-2836379775501347"; /* 300x250, created 10/23/09 */ google_ad_slot = "7146814087"; google_ad_width = 300; google_ad_height = 250; google_ad_region = "mkyongregion"; //-->

mkyong Founder of Mkyong.com, love Java and open source stuffs. Follow him on Twitter, or befriend him on Facebook or Google Plus. Here are some of my favorite books

Head First Java

Design Pattern

Effective Java

Spring Recipes

JavaScript Ninja

Related Posts Android Tutorial How to send Email in Android How to send SMS message in Android Android : how to check if device has camera How to turn on/off camera LED / flashlight in Android Popular Posts Top 8 Java People You Should Know Top 20 Java Websites Top 5 Free Java eBooks Top 10 Java Regular Expression Examples Top 5 Open Source Q&A Systems

You might also like following tutorials :

&#8592; Older Comments

Nima AhmadiJune 24, 2013 at 3:06 pm hey! nice job! but you should check the convertView before making a new rowView. Reply

RomainJune 25, 2013 at 6:12 am 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); } Reply

RomainJune 24, 2013 at 9:26 am THANK YOU SO MUCH! I ve been looking for an easy tutorial like yours for a while!! Thank you dude! Good job! Reply

paket wisata murahJune 17, 2013 at 5:26 pm nice coding, i likes Reply

JaneMay 24, 2013 at 3:15 pm THANK YOU Reply

RaheelMay 15, 2013 at 2:07 am 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.? Reply

AbdelrahmanMay 6, 2013 at 10:33 pm 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 Reply

JayanthApril 22, 2013 at 2:53 pm Thank you for the simple yet useful tutorial Reply

pavanApril 18, 2013 at 6:21 pm How to include a list under a list i mean sublisting Reply

kokoApril 14, 2013 at 5:57 pm thank for this helpful tutorial. how do i set a the setOnItemClickListener method in order to open a new activity. regards Reply

Android GuruApril 13, 2013 at 10:55 pm 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/ Reply

okfriansyahApril 4, 2013 at 12:19 am 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? Reply

Michael CohenMarch 28, 2013 at 5:03 am Thanks. Nice job! Reply

AbilashMarch 19, 2013 at 2:43 pm Thanks Reply

islealohaFebruary 28, 2013 at 6:28 am 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. Reply

islealohaFebruary 28, 2013 at 6:24 am

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

DavidFebruary 27, 2013 at 6:07 pm 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 | Reply

User0March 27, 2013 at 5:41 pm 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().getId entifier(uri, null, context.getPackageName())); Reply

Ssldke MalskeFebruary 1, 2013 at 4:10 am

Note To post source code in comment, uses

tag, for examples : Java source code here XML here Reply

Ssldke MalskeFebruary 1, 2013 at 4:09 am majde ndjh lsjkeio

Java source code here XML here Reply

AinaJanuary 12, 2013 at 6:04 pm thank you very much , can you tell me where I can get tutorial to start new activity from list view? Reply

akkiJanuary 11, 2013 at 1:43 pm 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 Reply

Rich MayoJanuary 8, 2013 at 2:28 am

Where is your software getting your list titles? I can t find or List of Mobile OS anywhere. Reply

List of Fruits

&#8592; Older Comments

What is your opinion? Cancel Reply Your email address will not be published. Required fields are marked * Name * Email * Website Comment Note To post source code in comment, uses <pre lang="java"> source code </pre>

Notify me of followup comments via e-mail

<!-- google_ad_client = "ca-pub-2836379775501347"; /* 300x250, created 7/12/08 */ google_ad_slot = "7072877400"; google_ad_width = 300; google_ad_height = 250; google_ad_region = "mkyongregion"; //-->

<!-- google_ad_client = "ca-pub-2836379775501347"; /* 300x250, created 8/5/08 */ google_ad_slot = "5738517670"; google_ad_width = 300; google_ad_height = 250; google_ad_region = "mkyongregion"; //-->

<!-- google_ad_client = "ca-pub-2836379775501347"; /* 160x600, created 10/4/09 */ google_ad_slot = "9218922650"; google_ad_width = 160; google_ad_height = 600; google_ad_region = "mkyongregion"; //-->

Do you know the answer? for(x in threads) { var jnpTitle = threads[x].title.replace("[OPEN]","<span class='open'>[OPEN]</span>"); jnpTitle = jnpTitle.replace("[SOLVED]","<span class='solved'>[SOLVED]</span>"); document.writeln("<li><p><a href=\"http://javanullpointer.com/showthread.php?t="+threads[x].threadid+"\" target=\"_blank\">"+jnpTitle+"</a></p></li>"); } [OPEN] How to know Dependencies of a module/library(for e.g. EclipseLink) when configuring it in JBoss 7.1 [SOLVED] Java : How to escape html tags in a string [OPEN] Pagination [OPEN] form base authentication in jsf. [OPEN] How to make a secure java jar file, means only authorized user's can access my jar....???? [OPEN] How Can I link XML Tags to database table colums ? [SOLVED] PropertyEditorSupport setter and getter is not called [OPEN] How to get input from user in any language P.S Above questions are from JavaNullPointer.com /* <![CDATA[ */ var _wpcf7 = {"loaderUrl":"http:\/\/www.mkyong.com\/wp-content\/plugins\/contact-form-7\/imag es\/ajax-loader.gif","sending":"Sendingn ...","cached":"1"}; /* ]]> */

All Available Tutorials Java Core Technologies : Java I/O, Java RegEx, Java XML, Java JSON, JDBC, Java Misc J2EE Frameworks : Hibernate, JSF 2.0, Spring Core, Spring MVC, Spring Security, Apache Wicket, Struts 1.x, Struts 2.x Web Service : JAX-WS (SOAP), JAX-RS (REST) Build Tools : Maven, Archiva Unit Test Frameworks : jUnit, TestNG

Others : Android, Google App Engine, jQuery, Java MongoDB, Quartz Scheduler

Favorites Links Android Developer Google App Engine using Java DZone - Fresh Links Official Java EE 5 Tutorial Official Java EE 6 Tutorial Spring 2.5.x documentation Spring 3.1.x documentation Hibernate core documentation Java SE 6.0 API documentation Java EE 6.0 API documentation Java Secure Socket Extension (JSSE) Reference Guide JSP home page JSF home page Eclipse IDE for Java developer Struts 1.3 documentation Struts 2.2 documentation Maven home page Maven central repository Search Java.Net Maven repository Ant home page JAX-WS Official Website JAX-RS Official Website (Jersey) MongoDB Official Website Friends & Links Java Code Geeks PHP Tutorials TenthOfMarch Web Security Blog Web Development About Us Mkyong.com is a weblog dedicated to Java/J2EE developers and Web Developers. We constantly publish useful tricks, tutorials on J2EE or web development. All examples are simple, easy to read, and full source code available, and of course well tested in our development environment. We're SocialTwitter - Follow Me Facebook - Like Me Google Plus - Add Me RSS - Subscribe Me Copyright 2008-2013 Mkyong.com, all rights reserved. Web Hosting Powered by Liquid Web var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-752408-5']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www')

+ '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); function _dmBootstrap(file) { var _dma = document.createElement('script'); _dma.type = 'text/javascript'; _dma.async = true; _dma.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + file; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(_dma); } function _dmFollowup(file) { if (typeof DMAds === 'undefined') _dmBootstrap('cdn2.DeveloperMedia.com/a.min.js');} (function () { _dmBootstrap('cdn1.DeveloperMedia.com/a.min.js'); setTimeout(_dmFollowup, 2000);})(); function w3tc_load_js(u){var d=document,p=d.getElementsByTagName('HEAD')[0],c=d.createElement('script');c.typ e='text/javascript';c.src=u;p.appendChild(c);}w3tc_load_js('http://www.mkyong.co m/wp-content/cache/minify/000000/481ba/default.include-footer.edcd0d.js');

Você também pode gostar