A ListView in Android is a view that groups several items and displays them in a vertical scrollable list. The list items are automatically inserted into the list using an Adapter that pulls content from a source such as an array or database. In this blog, we’ll learn how to use ListView in an Android app using Java.
Creating a ListView
To create a ListView, you first need to define it in your layout file:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Populating the ListView
To populate the ListView with data, you need to create an ArrayAdapter and set it to the ListView. Here’s how you can do it:
String[] listItems = new String[]{"Item 1", "Item 2", "Item 3"};
ListView listView = findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
In the above code, new String[]{"Item 1", "Item 2", "Item 3"}
is an array of strings that you want to display in the ListView.
Handling ListView Clicks
To handle the click event on list items, you need to set an OnItemClickListener
to the ListView:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = (String) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "Clicked: " + selectedItem, Toast.LENGTH_SHORT).show();
}
});
In the above code, when an item is clicked, a Toast message is displayed showing the clicked item.