Android ListView Tutorial

Author: | Posted in Android, Quick Tips No comments

In this Android ListView Tutorial we will learn how to use Android ListView to show array data as row wise scrollable view. The each row can be a View or a ViewGroup. The data is added to ListView using an Adapter. We will show names of cities in ListView, to add ListView on screen layout of any Activity or Fragment first we need to define it in their respective layout file as shown below.

<LinearLayout xmlns:android=""
android:orientation="vertical" >

and then use it in Activity class as below.

public class AndroidListViewTutorial extends Activity {
    ListView listView;
    Activity context = null;
    protected void onCreate(Bundle savedInstanceState) {
        context = this;
        // Find ListView object from xml
        listView = (ListView) findViewById(;
        // We will use String Array for values to show in ListView
        String[] values = new String[] { "Item 1", "Item 2", "Item 3",
                "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9" };
        // Define a new Adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,, values);
        // Set adapter to ListView
        // ListView OnItemClickListener
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // ListView Clicked item index
                int itemPosition = position;
                // ListView Clicked item value
                String itemValue = (String) listView
                // Show message on screen
                showToastMessage(context, "Position :" + itemPosition
                        + "  ListItem : " + itemValue);
    public static void showToastMessage(final Activity context,
            final String message) {
        context.runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
(Visited 231 times, 1 visits today)