Example Create Simple List View / ListView in Android


You better know about ListView while start learning Android. ListView will widely use in Android Development because scrollable of data is commonly used in creating applications. To use ListView, we should extends “ListActivity” rather than “Activity”. Basically, ListActivity is extending “Activity” to handle List of View.

Another keyword while using ListView is called “Adapter”. ListAdapter is used to managing data in ListView. So, when you create a list and you need to customize content / change design in rows of list, then you should use ListAdapter.

Now, create an Android Project. I create activity1.java in Apps -> Src -> App.NameSpace :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package myapp.android.namespace;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Activity1 extends ListActivity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String [] values = new String[] {"Hello", "World", "People"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
    }
   
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        String item = (String) getListAdapter().getItem(position);
        Toast.makeText(this, item + "selected", Toast.LENGTH_LONG).show();
    }
}

Run this code and you will got ListView. The explanation is here :

1. We create Activity1 which will first execute by Android Simulator and it use ListActivity.

2. We build content of List which will intepreted as rows using String Array

1
String [] values = new String[] {"Hello", "World", "People"};

3. ArrayAdapter will handle our String array and pass it into built-in ListView Layout simple_list_item1

1
android.R.layout.simple_list_item_1

4. We set list by “setListAdapter”

5. To make handler for Onclick and know the row content, we use “onListItemClick”.

Simple right ? 😀


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.