Android List View Example

A ListView in Android is a scrollable item that is displayed using an Adapter from an array or database. An example of this is the messaging system of a mobile phone.

In this tutorial, I will show you the basic of ListView. To avoid complex code, I will simply use an array instead of database to display the item in our ListView.

Now, create an Android project. If you don’t know how to create one, please follow our tutorial on how to “Create an Android Project Using Eclipse“.

Settings:

Application Name: List View
Project Name: listview
Package Name: com.sourcecodester.listview
Activity Name: ListView
Layout Name: main

If you have followed our previous tutorial, you will probably know the settings above.

Now, open and edit your ListView.java with the following code:

  1. package com.sourcecodester.listview;
  2.  
  3. import android.app.ListActivity;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.ArrayAdapter;
  7. import android.widget.Toast;
  8.  
  9. public class ListView extends ListActivity {
  10.         ListView listview;
  11.        
  12.         @Override
  13.         public void onCreate(Bundle savedInstanceState) {
  14.                 super.onCreate(savedInstanceState);
  15.                 setContentView(R.layout.main);
  16.  
  17.                 String[] values = new String[] { "Visual Basic", "C#", "C/C++",
  18.                         "PHP", "Foxpro", "Delphi", "Java", "Perl",
  19.                         "Ruby", "Cobol" };
  20.        
  21.                 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
  22.                                 android.R.layout.simple_list_item_1, values);
  23.                          
  24.                 setListAdapter(adapter);
  25.         }
  26.  
  27.         protected void onListItemClick(ListView l, View v, int position, long id) {
  28.                 String item = (String) getListAdapter().getItem(position);
  29.                 Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
  30.         }
  31.  
  32. }

And also open and edit your main.xml file that can be found under res/layout with the following code:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent"
  5.     android:orientation="vertical" >
  6.  
  7.     <ListView
  8.         android:id="@android:id/list"
  9.         android:layout_width="wrap_content"
  10.         android:layout_height="435dp" />
  11.  
  12. </LinearLayout>

Run and test your ListView. You will see the same result just like the image above.

Add new comment