5.3 Implementation of a ListView

While list views are not generally recommended, there will be situations where implementing a list view will save time and reduce file size. List views are used for small lists where the list is not expected to extend past the screen or when the individual cells in the list have simple layouts, like just a TextView.
For example, we used a list view to show the menu items of a specific eatery because the list of menu items is relatively short and does not require complex layouts.
In our example, we'll be creating a simple list that displays the menu items of Libe Cafe. We'll start by adding a ListView to the XML.
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Then we'll be using an Android supported adapter for the list view called ArrayAdapter, which takes in an array and displays it directly in list form.
MainActivity.kt
class MainActivity : AppCompatActivity() {
​
private var mainListView : ListView = null
private var listAdapter : ArrayAdapter<String> = null
​
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
var mainListView = findViewById<ListView>(R.id.userlist)
// Creating our list of menu items
var menuList =
arrayOf("Starbucks Coffee", "Tazo Tea", "Hot Cocoa", "Smoothies")
​
// Creating an ArrayAdapter
listAdapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_1, // built-in layout for list items
menuList
)
// Setting the adapter to the list view
mainListView.adapter = listAdapter
}
}
In the example above, you'll notice that you don't need many lines of code to create and populate a simple ListView which is why ListViews are viable solutions for simple views. As you will learn in the next section, creating a recycler view list will require more classes and more operations.