Android ListView is a view which groups several items and display them in vertical scrollable list.
The list items are automatically inserted to the list using an Adapter.
that pulls content from a source such as an array or database.
An adapter actually bridges between UI components and the data source that fill data into UI Component. Adapter holds the data and send the data to adapter view, the view can takes the data from adapter view and shows the data on different views like as spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to an Adapter, which retrieves data from an external source and creates a View that represents each data entry.
Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView ( i.e. ListView or GridView). The common adapters are ArrayAdapter,Base Adapter,CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and WrapperListAdapter. We will see separate examples for both the adapters.
You can use this adapter when your data source is an array. By default, ArrayAdapter creates a view for each array item by calling toString() on each item and placing the contents in a TextView. Consider you have an array of strings you want to display in a ListView, initialize a new ArrayAdapter using a constructor to specify the layout for each string and the string array −
Here are arguments for this constructor −
First argument this is the application context. Most of the case, keep it this.
Second argument will be layout defined in XML file and having TextView for each string in the array.
Final argument is an array of strings which will be populated in the text view.
Once you have array adapter created, then simply call setAdapter() on your ListView object as follows −
You will define your list view under res/layout directory in an XML file. For our example we are going to using activity_main.xml file.
Following is the example which will take you through simple steps to show how to create your own Android application using ListView. Follow the following steps to modify the Android application we created in Hello World Example chapter −
Following is the content of the modified main activity file src/com.example.ListDisplay/ListDisplay.java. This file can include each of the fundamental life cycle methods.
Following will be the content of res/layout/activity_main.xml file −
Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment set-up. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −