Android ListView

ListView is the mostly using component in Android to display any list of items. This tutorial explains the way to create a simple ListView application which displays all 23 design patterns and a short description about each of them. The official Android developers site defines the ListView as:
ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list.
Even though ListView can be used to display the database items, this article uses the ListView to display the data from a String array.

Step 1:
Create an Android project with a project name “ListView Sample” and a package name “com.javahelps.sample.simplelistview”.

Step 2:
Almost always ListView covers the entire screen of your application. Therefore, the parent layout is changed to the FrameLayout. FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. To change the layout open the activity_main.xml in the XML editor and replace the RelativeLayout by FrameLayout as shown here. If there is a default Hello World TextView, delete the TextView and move to the next step.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

</FrameLayout>
Step 3:
Drag and drop a ListView component from the Container palette to the center of the layout. As shown in the screen shot, drop into the [center, center] location of the FrameLayout.


Again move to the XML editor and change the width and height of the ListView to match_parent. Your final XML layout must be like this.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center" />
</FrameLayout>
Step 4:
Open the strings.xml file from the values directory. Copy and paste the following code into the file just above the </resources> tag.
<string-array name="design_patterns">
    <item>Abstract Factory</item>
    <item>Builder</item>
    <item>Factory Method</item>
    <item>Prototype</item>
    <item>Singleton</item>
    <item>Adapter</item>
    <item>Bridge</item>
    <item>Composite</item>
    <item>Decorator</item>
    <item>Facade</item>
    <item>Flyweight</item>
    <item>Proxy</item>
    <item>Chain of responsibility</item>
    <item>Command</item>
    <item>Interpreter</item>
    <item>Iterator</item>
    <item>Mediator</item>
    <item>Memento</item>
    <item>Observer</item>
    <item>State</item>
    <item>Strategy</item>
    <item>Template method</item>
    <item>Visitor</item>
</string-array>

<string-array name="design_patterns_description">
    <item>Groups object factories that have a common theme.</item>
    <item>Constructs complex objects by separating construction and representation.</item>
    <item>Creates objects without specifying the exact class to create.</item>
    <item>Creates objects by cloning an existing object.</item>
    <item>Restricts object creation for a class to only one instance.</item>
    <item>Allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.</item>
    <item>Decouples an abstraction from its implementation so that the two can vary independently.</item>
    <item>Composes zero-or-more similar objects so that they can be manipulated as one object.</item>
    <item>Dynamically adds/overrides behaviour in an existing method of an object.</item>
    <item>Provides a simplified interface to a large body of code.</item>
    <item>Reduces the cost of creating and manipulating a large number of similar objects.</item>
    <item>Provides a placeholder for another object to control access, reduce cost, and reduce complexity.</item>
    <item>Delegates commands to a chain of processing objects.</item>
    <item>Creates objects which encapsulate actions and parameters.</item>
    <item>Implements a specialized language.</item>
    <item>Accesses the elements of an object sequentially without exposing its underlying representation.</item>
    <item>Allows loose coupling between classes by being the only class that has detailed knowledge of their methods.</item>
    <item>Provides the ability to restore an object to its previous state (undo).</item>
    <item>Publish/subscribe pattern which allows a number of observer objects to see an event.</item>
    <item>Allows an object to alter its behavior when its internal state changes.</item>
    <item>Allows one of a family of algorithms to be selected on-the-fly at runtime.</item>
    <item>Defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.</item>
    <item>Separates an algorithm from an object structure by moving the hierarchy of methods into one object.</item>
</string-array>
This is a way to define String arrays in Android using the XML code. This code declares two arrays with identifier names design_patterns and design_patterns_description. Once you paste the code save all the modified files, otherwise the modifications you made will not be reflected in the MainActivity.java

Step 5:
Create an instance variable reference for ListView and two String array references inside the MainActivity class as given below.
private ListView listView;
private String[] designPatterns;
private String[] descriptions;
Step 6:
Use findViewById inside the onCreate method and assign the object of the ListView to the reference you have crated in Step 5.
// Find the list view
this.listView = (ListView) findViewById(R.id.listView);
Step 7:
Use getResources().getStringArray(int) method to find and assign the arrays we have declared in the strings.xml to the references we have created in Step 5.
// Create the arrays
this.designPatterns = getResources().getStringArray(R.array.design_patterns);
this.descriptions = getResources().getStringArray(R.array.design_patterns_description);
Step 8:
Create an object of ArrayAdapter as provided here and assign it to the ListView using the setAdapter method of ListView.
// Create an array adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, designPatterns);
listView.setAdapter(adapter);
In Android, Adapter is used to port a collection of data to the ListView. ArrayAdapter is a subclass of Adapter, used to provide an array of data to ListView or to any other similar components. ArrayAdapter can receive either an array of Objects or a List of Objects. From the Objects the toString method is called to get the String representation of the Object and which is displayed as the item in the ListView. The passed array elements are displayed in the same order as they are in the array.

Step 9:
Set the OnItemClickListener to ListView and call the Toast to display the relative description based on the index. The position passed to the onItemClick method is the zero based position of the items displayed in ListView. If the description array maintains the same order relative to the designPatterns array then it is easy to directly access the elements from the description array using the clicked position as the index. Retrieve the item description and display it using a Toast.
// Set item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String description = descriptions[position];
        Toast.makeText(MainActivity.this, description, Toast.LENGTH_SHORT).show();
    }
});
Finally your MainActivity.java should be similar to this code.
package com.javahelps.sample.simplelistview;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {
    private ListView listView;
    private String[] designPatterns;
    private String[] descriptions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Find the list view
        this.listView = (ListView) findViewById(R.id.listView);

        // Create the arrays
        this.designPatterns = getResources().getStringArray(R.array.design_patterns);
        this.descriptions = getResources().getStringArray(R.array.design_patterns_description);

        // Create an array adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, designPatterns);
        listView.setAdapter(adapter);

        // Set item click listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String description = descriptions[position];
                Toast.makeText(MainActivity.this, description, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
Ignore the onCreateOptionsMenu and onOptionsItemSelected methods which are created by Android by default for option menu of the Activity.

Step 10:
Save all and run the application.

For the completed project, click on this link.

Sample Problem
A partially completed Android application is provided at this link. This project downloads some quotes from the Internet and provide them as a List of Quotes. The received List of quotes are stored using an instance variable quotes in the MainActivity. You are required to create a ListView in the activity_main.xml and to display the quotes in the ListView. When user clicks on a specific quote, display the description of the quote using the showQuote(int index) method. The places you need to add your code have been commented in the MainActivity.java using the // TODO: comments. The expected output should be something like in this screenshot (You may get different set of quotes).


Note: This project needs Internet access, so when you run this application make sure that you have an active Internet connection.

Find the projects at Git Hub.
Previous
Next Post »

Contact Form

Name

Email *

Message *