Tutorial details

Android ListView – Tutorial and basic example | App Code for Sale | Preview

Android ListView – Tutorial and basic example | Android Tutorial

The basic concepts behind ListView and how to use it

Overview PAGE TOP

One of the UI component we use often is ListView, for example when we need to show items in a vertical scrolling list. One interesting aspect is this component can be deeply customized and can be adapted to our needs. In this first post i want to analyze the basic concepts behind it and how to use this component.

In order to show items inside the list, this component uses an adapter, so if we want to populate the list we have first create or use existing adapters. Android SDK has some standard adapters that are useful in many cases. If we have special needs we can create custom adapter and i will cover it in the next post. To understand how we can use this UI component we can suppose we want to show a list of planets. To make things simple and focus our attention on the ListView component we will use, by now

a very simple and basic adapter called SimpleAdapter.

So let’s create an android project with an activity called MainActivity and a layout called activity_main.xml. This layout is very simple, it just contains the listView component.

01  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
02      xmlns:tools="http://schemas.android.com/tools"
03      android:layout_width="match_parent"
04      android:layout_height="match_parent" >
06      <ListView android:id="@+id/listView"
07                android:layout_height="match_parent"
08                android:layout_width="match_parent"/>
10  </RelativeLayout>

Our MainActivity class is:

01  public class MainActivity extends Activity {
03      @Override
04      public void onCreate(Bundle savedInstanceState) {
05          super.onCreate(savedInstanceState);
06          setContentView(R.layout.activity_main);
07          ....
08      }
09  ...
10  }

So now it is the time to populate our listView. As said before we use a SimpleAdapter, a standard adapter present in SDK. Let’s suppose we want to show a list with the solar system planets. SimpleAdapter accepts a java.util.List with element’s type of java.util.Map. In our case we have then:

01  // The data to show
02  List<Map<String, String>> planetsList = new ArrayList<Map<String,String>>();
04  .....
06     private void initList() {
07      // We populate the planets
09      planetsList.add(createPlanet("planet", "Mercury"));
10      planetsList.add(createPlanet("planet", "Venus"));
11      planetsList.add(createPlanet("planet", "Mars"));
12      planetsList.add(createPlanet("planet", "Jupiter"));
13      planetsList.add(createPlanet("planet", "Saturn"));
14      planetsList.add(createPlanet("planet", "Uranus"));
15      planetsList.add(createPlanet("planet", "Neptune"));
17  }
19  private HashMap<String, String> createPlanet(String key, String name) {
20      HashMap<String, String> planet = new HashMap<String, String>();
21      planet.put(key, name);
23      return planet;
24  }

and the SimpleAdapter can be instantiated as:

1   // This is a simple adapter that accepts as parameter
2   // Context
3   // Data list
4   // The row layout that is used during the row creation
5   // The keys used to retrieve the data
6   // The View id used to show the data. The key number and the view id must match
7   simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"planet"}, new int[] {android.R.id.text1});

where the first parameter is the context reference (our Activity), the second the data we want so show in the list. The 3rd is the layout we want to use for each row in the list. In this case we just used a pre-built layout shipped with android SDK that you can find inside the android sdk directroy and then platforms\android-16\data\res\layout. This is a very simple layout that contains just a TextView with id text1. The 4th parameter is an array of key used to retrieve the data from the Map. Each list element of java.util.List represents a row in the ListView and each element inside the row must have a unique key that is used to retrieve the element content. In our case to make things very simple we just used planet as key. The 5th element is an array of int representing the ids of the View inside the row layout. In our case is just text1 id. Please notice that the keys array length must match the ids array length.

We have almost done. Let’s modify the onCreate method in our Activity like that:

01  @Override
02  public void onCreate(Bundle savedInstanceState) {
03      super.onCreate(savedInstanceState);
04      setContentView(R.layout.activity_main);
06      initList();
08      // We get the ListView component from the layout
09      ListView lv = (ListView) findViewById(R.id.listView);
11      // This is a simple adapter that accepts as parameter
12      // Context
13      // Data list
14      // The row layout that is used during the row creation
15      // The keys used to retrieve the data
16      // The View id used to show the data. The key number and the view id must match
17      simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, newString[] {"planet"}, new int[] {android.R.id.text1});
19      lv.setAdapter(simpleAdpt);
20  }

If we run our project we have:


User interaction

Once we have created our list and populated it with the items we want to interact with the user giving the chance to click one item or maybe show a context menu. To do it we have to register some listener.

If we want to listen when the user clicks on an item we simply have to implement the AdapterView.OnItemClickListener(). So we have:

01  // React to user clicks on item
02  lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
04       public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
05                               long id) {
07           // We know the View is a TextView so we can cast it
08           TextView clickedView = (TextView) view;
10           Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
12       }
13  });

When the user clicks on an item we simply show the position and the id of the item clicked using a simple Toast.

What about if we want to create a context menu when a user long click on an item? Well this is very simple because we have to override the onCreateContextMenu method in the Activity class and register the class as listener. First override the method:

01  // We want to create a context Menu when the user long click on an item
02    @Override
03    public void onCreateContextMenu(ContextMenu menu, View v,
04            ContextMenuInfo menuInfo) {
06        super.onCreateContextMenu(menu, v, menuInfo);
07        AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
09        // We know that each row in the adapter is a Map
10        HashMap map =  (HashMap) simpleAdpt.getItem(aInfo.position);
12        menu.setHeaderTitle("Options for " + map.get("planet"));
13        menu.add(1, 1, 1, "Details");
14        menu.add(1, 2, 2, "Delete");
16    }

What do we do in this method? Well first we call super to let the SO makes its work. Then we cast the ContextMenuInfo to AdapterContextMenuInfo because we are using a ListView. The AdapterContextMenuInfo has an attribute that olds the item position clicked se we use this information to retrieve the item information. We know we are using an HashMap to represent the row so we cast the result to HashMap. It is the time we create the menu.

First we create the menu header using the name of the planet retrieved using the HashMap and then set two options “Details” and “Delete” with different ids but belonging to the same group we called “1”.

Before running our project we have to modify onCreate method to register our MainClass as the handler for the context menu for the ListView.

Reference PAGE TOP


0 Comments Leave a comment

Please login in order to leave a comment.

Newest first

to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.