ListView is used for arranging items in a vertical and scrollable list. ListViews are commonly used to display a large set of similar data.

For example, displaying list of contacts. Item/row is represented by a single item view. This pattern is quite handy as it shows several contacts on screen at the same time. Its helps displaying list of data in a very simple and scrollable manner.

The simplest way to display a list view is using ArrayAdapter class . You can add lists or arrays of custom objects to it and these objects are referenced using index and displayed in the TextView of ListView.

We set the ArrayAdapter to the ListView to display the items of array adapter in it .

The following example explains the usage of ListView using ArrayAdapter.

Step1: Create the xml for the activity which contains a ListView

main.xml

 

<RelativeLayout 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"
tools:context=".AdapterActivity" >

<ListView
android:id="@+id/list_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="80dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</ListView>

</RelativeLayout>

Step 2: Create the Activity and use the code mentioned below.

• Create the ArrayAdapter and add a default layout list style and string array of data to it.
• Set ListView adapter as the ArrayAdapter.
• You can set listeners on your list view also.

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AdapterActivity extends Activity {
ListView listView;

static final String[] numbers = new String[] {
"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen",
"fifteen","sixteen","seventeen","eighteen",
"nineteen","twenty","twenty one","twenty two"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list_id);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);

listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
}
});
}

}

 

 

You can also download the above ListView Example here.

Screenshot: