Android ListView Tutorial with Kotlin
In this tutorial, you’ll learn how to use Android’s ListView to easily create scrollable lists, by creating a simple recipe list app using Kotlin. By Joe Howard.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Android ListView Tutorial with Kotlin
25 mins
Building Adapters
Okay, now that you’ve dabbled in theory, you can get on with building your very own adapter.
Create a new class by right-clicking on the com.raywenderlich.alltherecipes package and selecting New > Kotlin File/Class. Name it RecipeAdapter and define it with the following:
class RecipeAdapter : BaseAdapter() {
}
You’ve made the skeleton of the adapter. It extends the BaseAdapter
class, which requires several inherited methods you’ll implement after taking care of one more detail.
Update the RecipeAdapter
class as follows:
class RecipeAdapter(private val context: Context,
private val dataSource: ArrayList<Recipe>) : BaseAdapter() {
private val inflater: LayoutInflater
= context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
}
In here, you’ve added the properties that will be associated with the adapter and defined a primary constructor for RecipeAdapter
.
Your next step is to implement the adapter methods. Kick it off by placing the following code at the bottom of RecipeAdapter
:
//1
override fun getCount(): Int {
return dataSource.size
}
//2
override fun getItem(position: Int): Any {
return dataSource[position]
}
//3
override fun getItemId(position: Int): Long {
return position.toLong()
}
//4
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
// Get view for row item
val rowView = inflater.inflate(R.layout.list_item_recipe, parent, false)
return rowView
}
Here’s a step-by-step breakdown:
-
getCount()
lets ListView know how many items to display, or in other words, it returns the size of your data source. -
getItem()
returns an item to be placed in a given position from the data source, specifically,Recipe
objects obtained fromdataSource
. - This implements the
getItemId()
method that defines a unique ID for each row in the list. For simplicity, you just use the position of the item as its ID. - Finally,
getView()
creates a view to be used as a row in the list. Here you define what information shows and where it sits within the ListView. You also inflate a custom view from the XML layout defined inres/layout/list_item_recipe.xml
— more on this in the next section.
Defining the Layout of the ListView’s Rows
You probably noticed that the starter project comes with the file res/layout/list_item_recipe.xml
that describes how each row in the ListView should look and be laid out.
Below is an image that shows the layout of the row view and its elements:
Your task is to populate each element of the row view with the relevant recipe data, hence, you’ll define what text goes in the “title” element, the “subtitle” element and so on.
In the getView()
method, add the following code snippet just before the return statement:
// Get title element
val titleTextView = rowView.findViewById(R.id.recipe_list_title) as TextView
// Get subtitle element
val subtitleTextView = rowView.findViewById(R.id.recipe_list_subtitle) as TextView
// Get detail element
val detailTextView = rowView.findViewById(R.id.recipe_list_detail) as TextView
// Get thumbnail element
val thumbnailImageView = rowView.findViewById(R.id.recipe_list_thumbnail) as ImageView
This obtains references to each of the elements (or subviews) of the row view, specifically the title, subtitle, detail and thumbnail.
Now that you’ve got the references sorted out, you need to populate each element with relevant data. To do this, add the following code snippet under the previous one but before the return statement:
// 1
val recipe = getItem(position) as Recipe
// 2
titleTextView.text = recipe.title
subtitleTextView.text = recipe.description
detailTextView.text = recipe.label
// 3
Picasso.with(context).load(recipe.imageUrl).placeholder(R.mipmap.ic_launcher).into(thumbnailImageView)
Here’s what you’re doing in the above snippet:
- Getting the corresponding recipe for the current row.
- Updating the row view’s text views so they are displaying the recipe.
- Making use of the open-source Picasso library for asynchronous image loading — it helps you download the thumbnail images on a separate thread instead of the main thread. You’re also assigning a temporary placeholder for the
ImageView
to handle slow loading of images.
Now open up MainActivity so that you can get rid of the old adapter. In onCreate
, replace everything below (but not including) this line:
val recipeList = Recipe.getRecipesFromFile("recipes.json", this)
With:
val adapter = RecipeAdapter(this, recipeList)
listView.adapter = adapter
You just replaced the rather simple ArrayAdapter
with your own RecipeAdapter
to make the list more informative.
Build and run and you should see something like this:
Now you’re cooking for real! Look at those recipes — thumbnails and descriptions sure make a big difference.
Styling
Now that you’ve got the functionality under wraps, it’s time to turn your attention to the finer things in life. In this case, your finer things are elements that make your app more snazzy, such as compelling colors and fancy fonts.
Start with the fonts. Look for some custom fonts under res/font. You’ll find three font files: josefinsans_bold.ttf, josefinsans_semibolditalic.ttf and quicksand_bold.otf.
Open RecipeAdapter.java and go to the getView()
method. Just before the return statement, add the following:
val titleTypeFace = ResourcesCompat.getFont(context, R.font.josefinsans_bold)
titleTextView.typeface = titleTypeFace
val subtitleTypeFace = ResourcesCompat.getFont(context, R.font.josefinsans_semibolditalic)
subtitleTextView.typeface = subtitleTypeFace
val detailTypeFace = ResourcesCompat.getFont(context, R.font.quicksand_bold)
detailTextView.typeface = detailTypeFace
In here, you’re assigning a custom font to each of the text views in your rows’ layout. You access the font by creating a Typeface
, which specifies the intrinsic style and typeface of the font, by using ResourcesCompat.getFont()
. Next you set the typeface
for the corresponding TextView
to set the custom font.
Now build and run. Your result should look like this:
On to sprucing up the colors, which are defined in res/values/colors.xml. Open up RecipeAdapter and add the following below the inflater
declaration:
companion object {
private val LABEL_COLORS = hashMapOf(
"Low-Carb" to R.color.colorLowCarb,
"Low-Fat" to R.color.colorLowFat,
"Low-Sodium" to R.color.colorLowSodium,
"Medium-Carb" to R.color.colorMediumCarb,
"Vegetarian" to R.color.colorVegetarian,
"Balanced" to R.color.colorBalanced
)
}
You’ve created a hash map that pairs a recipe detail label with the resource id of a color defined in colors.xml.
Now go to the getView()
method, and add this line just above the return statement:
detailTextView.setTextColor(
ContextCompat.getColor(context, LABEL_COLORS[recipe.label] ?: R.color.colorPrimary))
Working from the inside out:
- Here you get the resource id for the color that corresponds to the
recipe.label
from theLABEL_COLORS
hash map. -
getColor()
is used inside ofContextCompat
to retrieve the hex color associated with that resource id. - Then you set the color property of the
detailTextView
to the hex color.
Build and run. Your app should look like this: