Android Android Kotlin

BaseAdapter with Android ListView using Kotlin5 min read

ListView is a ViewGroup that displays a list of vertically scrollable items. The list items are automatically inserted into the list using an adapter that is connected to a source, such as an array or a database query, and each item is converted into a row in the ListView.

BaseAdapter

BaseAdapter, as it’s name implies, is the base class for so many concrete adapter implementations on Android. It is abstract and therefore, cannot be directly instantiated.

BaseAdapter with Android ListView using Kotlin
BaseAdapter with Android ListView using Kotlin

Using the BaseAdapter




To use the BaseAdapter with a ListView, a concrete implementation the BaseAdapter class that implements the following methods must be created:

  • int getCount()
  • Object getItem(int position)
  • long getItemId(int position)
  • View getView(int position, View convertView, ViewGroup parent)

Before we create our custom BaseAdapter implementation, we need to create the layout for the ListView row and also a model for the items in the ListView.

Create model class

Each of our ListView rows will conatain an Person name, image and birthDate, so our Model class is as follows:

Person.kt

ListView row and activity_main layouts

The xml file for the rows of the listview created in the res/layout folder is shown below: 

activity_main.xml

listview_item.xml

Create the custom BaseAdapter implementation

Using the custom Adapter

The adapter can simply be used by instantiating it with the required paramters and set as the listview’s adapter.

Output:

ListView Optimization

To optimize the listview’s performance, a new row layout should be inflated only when convertView == null. This is because the adapter’s getView method is called whenever the listview needs to show a new row on the screen. The convertView gets recycled in this process. Hence, the row layout should be inflated just once when convertView == null, and it contents should be updated on subsequent getView calls, instead of inflating a new row on each call which is very expensive.

Source: https://guides.codepath.com/android/Using-a-BaseAdapter-with-ListView#create-the-custom-baseadapter-implementation

Leave a Comment