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="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>

and then use it in Activity class as below.

public class AndroidListViewTutorial extends Activity {
    ListView listView;
    Activity context = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_list_view_tutorial);
        context = this;
        // Find ListView object from xml
        listView = (ListView) findViewById(R.id.list);
        // 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, android.R.id.text1, values);
        // Set adapter to ListView
        listView.setAdapter(adapter);
        // ListView OnItemClickListener
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            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
                        .getItemAtPosition(position);
                // Show message on screen
                showToastMessage(context, "Position :" + itemPosition
                        + "  ListItem : " + itemValue);
            }
        });
    }
    public static void showToastMessage(final Activity context,
            final String message) {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            }
        });
    }
}