Android: Creating and populating ListView items in XML

3 September 2012 By Nithya Vasudevan 67,160 views 5 Comments
13 Flares Twitter 0 Facebook 3 Google+ 10 13 Flares ×

Project Description

  • In this Android tutorial, we will create an example to create ListView in XML layout file.
  • To load the entries we use android:entries attribute on list view element which points to the <string-array> defined by external resource in res/values/strings.xml.
  • Instead of loading the entries programatically using adapters (more specifically ArrayAdapter or CursorAdaptor) we have used XML layout file.
  • This approach is good, if your list items are simple string values (TextView).
  • Here, we are going to implement OnItemClickListener event listener which calls onItemClick() callback method where we retrieve and display the item selected by the user.

Environment Used

  • JDK 6 (Java SE 6)
  • Eclipse Indigo IDE for Java EE Developers (3.7.1)
  • Android SDK 4.0.3 / 4.1 Jelly Bean
  • Android Development Tools (ADT) Plugin for Eclipse (ADT version 20.0.0)
  • Refer this link to setup the Android development environment

Prerequisites

Create Android Project

  • Create a new Android Project and name it as “ListViewDemo“.
  • Enter the package name as “com.theopentutorials.android“.
  • Enter the Activity name as “ListViewActivity1“.
  • Click Finish.

strings.xml

Open res/values/string.xml and replace it with following content.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, ListViewActivity1!</string>
    <string name="app_name">ListViewDemo</string>
     <string-array name="sports_array">
        <item>Shuttle Badminton</item>
        <item>Tennis</item>
        <item>FootBall</item>
        <item>Basket Ball</item>
        <item>Table Tennis</item>
        <item>Chess</item>
        <item>Hockey</item>
    </string-array>
</resources>

The <string-array> element defines the list of strings that will be displayed as list item in the ListView layout.

XML layout file

Open main.xml file in res/layout and copy the following content.

<?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” >

     <ListView
        android:id=”@+id/sportsList”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content” 
        android:entries="@array/sports_array" 
	/>
</LinearLayout>

In the XML layout file we have defined a ListView for displaying a scrollable list of items. These items can be of any type and for this example we have used string (TextView object) as each item. To load the entries we have used android:entries=”@array/sports_array” attribute on list view element which points to the <string-array> resource defined in res/values/strings.xml.

Activity class

package com.theopentutorials.android;

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

public class ListViewActivity1 extends Activity implements OnItemClickListener{
    ListView listView;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        listView = (ListView) findViewById(R.id.sportsList);
        listView.setOnItemClickListener(this);        
    }

    /*
     * Parameters:
		adapter - The AdapterView where the click happened.
		view - The view within the AdapterView that was clicked
		position - The position of the view in the adapter.
		id - The row id of the item that was clicked.
     */
	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
		Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
	  	          Toast.LENGTH_SHORT).show();
	}
}
  • We used ListView inside Activity. To retrieve the UI widget defined in XML layout file we use findViewById(int id) referring the listview’s id.
  • We register the list view to OnItemClickListener using setOnItemClickListener method. When an item in the ListView is clicked, onItemClick() method is called and a Toast message is displayed, using the text from the clicked item. Since we have used array of string objects, each item in the list view references a TextView object.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.theopentutorials.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ListViewActivity1"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output

Run your application

Project Folder Structure

The complete folder structure of this example is shown below.

Tags: , , , , , , , , , , ,

  • moha

    i want to design a right to left listview.
    but i don’t know to create this.

  • gaurav

    thanks for the tutorial,
    I have a doubt,
    can u tell me that how to access or show text after clicking an item from the listview.
    For that i have created a raw folder and put .txt files,
    now i want to read respective file on particular item selected form list.
    public void onItemClick(AdapterView parent, View v,int position, long id)
    switch (position){
    case 0:{
    // code to read respective .txt file
    }
    break;
    case 1:{
    // code to read respective .txt file
    }
    break;
    default;
    ……….
    thank you in advance

  • Pingback: setOnItemClickListener for ListView in a fragment | Stackforum.com

  • fikriyogi

    how to start another activity using intent? not toast,

    @Override
    public void onItemClick(AdapterView adapter, View view, int position, long id) {
    Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
    Toast.LENGTH_SHORT).show();
    }

  • maniix

    YOU FUCKING UDACITY STUPID PEOPLE, THIS SHIT WAS POSTED ON FUCKING 2012!! ARE YOU FUCKING STUPID OR SOMETHING???