Android RecyclerView Tutorial with Kotlin

Learn how to display datasets of large or unknown size in this Android RecyclerView tutorial using Kotlin!


  • Kotlin 1.1, Android 4.4, Android Studio 3

Update note: This tutorial has been updated to Kotlin, Android 26 (Oreo) and Android Studio 3.0 by Rod Biresch. The original tutorial was written by Darryl Bayliss.

Recycling is one of those things that is good for the planet, and it’s a common sense way to make sure we don’t find ourselves buried in our own rubbish or without sufficient resources in the future.

A few Android engineers thought about the benefits of recycling and realized that an OS can also run more efficiently if it recycles. The result of this inspiration was millions of eco-Warriors and recycling enthusiasts rejoicing when the RecyclerView widget was introduced into Android Lollipop — or something like that. :]

There was even more celebration when Google announced a support library to make this clean, green, recycling machine backwards compatible all the way to Android Eclair (2.2), which was released back in 2010!

In this tutorial, you’re going to experience the power of RecyclerView in action and learn:

  • The purpose of a RecyclerView
  • The components that make up a RecyclerView
  • How to change the layout of a RecyclerView
  • How to add some nice animations to your RecyclerView

You’re also going to blast off into outer space with the sample app Galacticon. You’ll use it to build out a feed of daily astronomy photos from a public NASA API.

Prerequisites: You should have a working knowledge of developing for Android with Kotlin before working through this tutorial. If you need a refresher, take a look at some of our introductory tutorials! Also, you will need Android Studio 3.0 or greater.

Heading to Cape Canaveral: Getting Started

Download the starter project and open it up in Android Studio. There isn’t much to it yet, nor is the almighty RecyclerView anywhere to be seen.

Click the Run app button at the top and you’ll see something that resembles outer space in all the wrong ways:

It’s empty, but that’s ok. You wouldn’t learn much if all the work was done for you! Before you can add that amazing astrophotography from NASA, you’ll need to do some set up work.

Obtaining The (API) Keys to the Shuttle

You’ll use the Astronomy Picture of the Day API, one of the most popular web services provided by NASA. To ensure it doesn’t fall victim to unsolicited traffic, the service requires you to have an API key to use it in an application.

Fortunately, getting a key is as simple as putting your name and email address into and copying the API key that appears on the screen or the email sent to you.

Once you’ve acquired your API key, copy it and open the strings.xml file in your project. Paste your API key into the api_key string resource, replacing INSERT API KEY HERE:

4. API_KEY paste

Space Oddity: Learning About RecyclerView

You’re about to blast off into outer space to explore the vastness of RecyclerViews, but no competent commander heads into the unknown without preparation. You have questions, and you need answers before you go any further. Consider this section as your mission brief.

A RecyclerView can be thought of as a combination of a ListView and a GridView. However, there are extra features that separate your code into maintainable components even as they enforce memory-efficient design patterns.

But how could it be better than the tried and tested ListView and GridView you’re used to? Could it be some kind of alien technology? The answers, as always, are in the details.

Why You Need RecyclerView

Imagine you’re creating a ListView where the custom items you want to show are quite complicated. You take time to lovingly create a row layout for these items, and then use that layout inside your adapter.

Inside your getView() method, you inflate your new item layout. You then reference every view within by using the unique ids you provided in your XML to customize and add some view logic. Once finished, you pass that view to the ListView, ready to be drawn on the screen. All is well…or is it?

The truth is that ListViews and GridViews only do half the job of achieving true memory efficiency. They recycle the item layout, but don’t keep references to the layout children, forcing you to call findViewById() for every child of your item layout every time you call getView().

All this calling around can become very processor-intensive, especially for complicated layouts. Furthermore, the situation can cause your ListView scrolling to become jerky or non-responsive as it frantically tries to grab references to the views you need.


Android engineers initially provided a solution to this problem on the Android Developers site with smooth scrolling, via the power of the View Holder pattern.

When you use this pattern, you create a class that becomes an in-memory reference to all the views needed to fill your layout. The benefit is you set the references once and reuse them, effectively working around the performance hit that comes with repeatedly calling findViewById().


The problem is that it’s an optional pattern for a ListView or GridView. If you’re unaware of this detail, then you may wonder why your precious ListViews and GridViews are so slow.

First Contact: RecyclerView and Layouts

The arrival of the RecyclerView changed everything. It still uses an Adapter to act as a data source; however, you have to create ViewHolders to keep references in memory.

When you need a new view, it either creates a new ViewHolder object to inflate the layout and hold those references, or it recycles one from the existing stack.

Now you know why it’s called a RecyclerView!

Another perk of using RecyclerViews is that they come with default animations that you don’t have to create or add yourself — they just work.

Thanks to the requirement for a ViewHolder, the RecyclerView knows exactly which animation to apply to which item. Best of all, it just does it as required. You can even create your own animations and apply them as needed.

The last and most interesting component of a RecyclerView is its LayoutManager. This object positions the RecyclerView’s items and tells it when to recycle items that have transitioned off-screen.

Layout Managers come in three default flavors:

  • LinearLayoutManager positions your items to look like a standard ListView
  • GridLayoutManager positions your items in a grid format similar to a GridView
  • StaggeredGridLayoutManager positions your items in a staggered grid format.

You can also create your own LayoutManagers to use with a RecyclerView if you want an extra bit of customization.

Hopefully that answers all your questions, commander. Now, onto the mission!

Preparing for Launch: Creating the RecyclerView

To create the RecyclerView, you’ll break the work into four parts:

  1. Declare the RecyclerView in an activity layout and reference it in your activity Kotlin file.
  2. Create a custom item XML layout for your RecyclerView to use for its items.
  3. Create the view holder for your view items, hook up the data source of the RecyclerView and handle the view logic by creating a RecyclerView Adapter.
  4. Attach the adapter to the RecyclerView.

Step one should be familiar. Open up the activity_main.xml layout file, and add the following as a child of the LinearLayout:


Here you’re setting up the layout and telling the RecyclerView to match its parent.

Note: You’re using the v7 support library for backwards compatibility with older devices. The starter project already adds the RecyclerView Support Library as a dependency in your app’s build.gradle file. If you want more information on how to do it yourself, check out the Android developer website.

Open MainActivity.kt and declare the following property at the top of the class:

private lateinit var linearLayoutManager: LinearLayoutManager

In onCreate(), add the following lines after setContentView:

linearLayoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = linearLayoutManager

Android Studio should prompt you to import* for recyclerView. You may wonder how do we have a reference to recyclerView without first finding the view, i.e. findViewById()? The project has been configured to use Kotlin Android Extensions plugin. This plugin enables the ability to import views in a layout as “synthetic” properties.


The recyclerView is now an extension property for Activity, and it has the same type as declared in activity_main.xml. The plugin removes a lot of boilerplate code and reduces the risk of potential bugs.

Phase one of ignition is complete! You’ve declared and allocated memory for two parts of the puzzle that RecyclerViews need to work: The RecyclerView and its Layout Manager.

Ignition Phase 2: Laying out the RecyclerView Items

Phase two of ignition involves creating a custom layout for the item you want your RecyclerView to use. It works exactly the same as it does when you create a custom layout for a ListView or Gridview.

Head over to your layout folder and create a new layout with the name recyclerview_item_row and set the root element as a LinearLayout. In your new layout, add the following XML elements as children of your LinearLayout:

    android:adjustViewBounds="true" />

    tools:text="Some date" />

    android:maxLines="5" />

No rocket science here: You declared a few views as children of your layout, and can now use them in your adapter.

Adapters: Rocket Fuel for Your RecyclerView

Right-click on the com.raywenderlich.galacticon folder, select New \ Kotlin File/Class, and name it RecyclerAdapter and select Class for Kind. At the top of the file below the package declaration, import the support library’s version of RecyclerView:


Make the class extend RecyclerView.Adapter so it looks like the following:

class RecyclerAdapter : RecyclerView.Adapter<RecyclerAdapter.PhotoHolder>()  {

Android Studio will detect that you’re extending a class that has required methods and will underline your class declaration with a red squiggle.

To resolve this, click on the line of code to insert your cursor, then press Option + Return (or Alt + Enter on a PC) to bring up a context menu. Select Implement Methods:


Confirm you want to implement the suggested methods by clicking OK:

These methods are the driving force behind your RecyclerView adapter. Note how there is still a compiler error for the moment– this is because your adapter and the required methods are actually defined using your ViewHolder class, PhotoHolder, which doesn’t exist just yet. You’ll get to define your ViewHolder and see what each required method does shortly, so just hang tight, Commander!

As with every adapter, you need to provide the corresponding view a means of populating items and deciding how many items there should be.

Item clicks were previously managed by a ListView’s or GridView’s onItemClickListener. A RecyclerView doesn’t provide methods like this because it has one focus: ensuring the items inside are positioned properly and managed efficiently.

The job of listening for actions is now the responsibility of the RecyclerView item and its children. This may seem like more overhead, but in return, you get fine-grained control over how your item’s children can act.

At the top of your RecyclerAdapter class, add a variable photos to hold your photos in the primary constructor:

class RecyclerAdapter(private val photos: ArrayList<Photo>) RecyclerView.Adapter<RecyclerAdapter.PhotoHolder>() {

Nice job, Commander! Your adapter now knows where to look for data. Soon you’ll have an ArrayList of photos filled with the finest astrophotography!

Next, you’ll populate the stubbed methods that were added by Android Studio.

The first method, getItemCount(), is pretty simple and should be familiar from your work with ListViews or GridViews.

The adapter will work out how many items to display. In this case, you want the adapter to show every photo you’ve downloaded from NASA’s API. To do that, add update getItemCount() to the following:

override fun getItemCount() = photos.size

Next, you’re going to exploit the ViewHolder pattern to make an object that holds all your view references.

Velcro For All: Keeping Hold Of Your Views

To create a PhotoHolder for your view references, you’ll create a nested class in your adapter. You’ll add it here rather than in a separate class because its behavior is tightly coupled with the adapter. First, import synthetic properties for the recycler view item so you can reference the view properties:


Add the following code at the bottom of the RecyclerAdapter class:

class PhotoHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {
  private var view: View = v
  private var photo: Photo? = null

  init {

  override fun onClick(v: View) {
    Log.d("RecyclerView", "CLICK!")

  companion object {
    private val PHOTO_KEY = "PHOTO"

So what did you do here?

  1. Made the class extend RecyclerView.ViewHolder, allowing it to be used as a ViewHolder for the adapter.
  2. Added a reference to the lifecycle of the object to allow the ViewHolder to hang on to your View, so it can access the ImageView and TextView as an extension property. Kotlin Android Extensions plugin adds in hidden caching functions and fields so that views are not constantly queried.
  3. Initialized the View.OnClickListener.
  4. Implemented the required method for View.OnClickListener since ViewHolders are responsible for their own event handling.
  5. Added a key for easier reference to the particular item being used to launch your RecyclerView.

You should still have a compiler errors with onBindViewHolder and onCreateViewHolder methods. Change the holder: ? argument on onBindViewHolder to have a type RecyclerAdapter.PhotoHolder.

override fun onBindViewHolder(holder: RecyclerAdapter.PhotoHolder, position: Int) {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.

Then add a RecyclerAdapter.PhotoHolder return type to the onCreateViewHolder method and remove the safe call operator (i.e. ?) of the parent argument type.

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerAdapter.PhotoHolder {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.

You should now be able to build and run the app again, but it’ll look about the same because you haven’t told the RecyclerView how to associate the PhotoHolder with a view.

Assembling The Pieces

Sometimes there are no ViewHolders available. In this scenario, RecylerView will ask onCreateViewHolder() from RecyclerAdapter to make a new one. You’ll use the item layout — PhotoHolder — to create a view for the ViewHolder.

The inflate code could simply be added to onCreateViewHolder(). However, this is a nice opportunity to show a really cool Kotlin feature called Extensions.

First, add a new Kotlin file named Extensions.kt to the project and then add the following new extension function to the new file:

fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
    return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)

Replace the TODO("not implemented") line between the curly braces in onCreateViewHolder() with the following:

val inflatedView = parent.inflate(R.layout.recyclerview_item_row, false)
return PhotoHolder(inflatedView)

Here you inflate the view from its layout and pass it in to a PhotoHolder. The parent.inflate(R.layout.recyclerview_item_row, false) method will execute the new ViewGroup.inflate(...) extension function to inflate the layout.

And with that, you’ve made it so the object holds onto those references while it’s recycled, but there are still more pieces to put together before you can launch your rocketship.

Start a new activity by replacing the log in ViewHolder’s onClick with this code:

val context = itemView.context
val showPhotoIntent = Intent(context,
showPhotoIntent.putExtra(PHOTO_KEY, photo)

This grabs the current context of your item view and creates an intent to show a new activity on the screen, passing the photo object you want to show. Passing the context object into the intent allows the app to know what activity it is leaving.

Next thing to do is to add this method inside PhotoHolder:

fun bindPhoto(photo: Photo) { = photo
  view.itemDate.text = photo.humanDate
  view.itemDescription.text = photo.explanation

This binds the photo to the PhotoHolder, giving your item the data it needs to work out what it should show.

It also adds the suggested Picasso import, which is a library that makes it significantly simpler to get images from a given URL.

The last piece of the PhotoHolder assembly will tell it how to show the right photo at the right moment. It’s the RecyclerAdapter’s onBindViewHolder, and it lets you know a new item will be available on screen and the holder needs some data.

Add the following code inside the onBindViewHolder() method:

val itemPhoto = photos[position]

Here you’re passing in a copy of your ViewHolder and the position where the item will show in your RecyclerView, and calling bindPhoto(...).

And that’s all you needed to do here on the assembly — just use the position where your ViewHolder will appear to grab the photo out of your list, and then pass it to your ViewHolder.

Step three of your ignition check protocol is complete!

Countdown And Liftoff: Hooking up the Adapter And RecyclerView

This is the moment you’ve been waiting for, the final stage before blast off! All you need to do is hook your adapter up to your RecyclerView and make sure it retrieves photos when it’s created so you can explore space — in pictures.

Open MainActivity.kt, and add this property at the top:

private lateinit var adapter: RecyclerAdapter

Next, underneath the assignment of recyclerView.layoutManager, add the following:

adapter = RecyclerAdapter(photosList)
recyclerView.adapter = adapter

Here you’re creating the adapter, passing in the constructors it needs and setting it as the adapter for your RecyclerView.

Although the adapter is connected, there’s one more thing to do to make sure you don’t have an empty screen.

In onStart(), underneath the call to super, add this code:

if (photosList.size == 0) {

This adds a check to see if your list is empty, and if yes, it requests a photo.

Next, in receivedNewPhoto(), update the method so it looks like the following:

override fun receivedNewPhoto(newPhoto: Photo) {
  runOnUiThread {

Here you are informing the recycler adapter that an item was added after the list of photos was updated.

Now you’re ready to commence the ignition sequence, er…I mean run the app.

Run the app, load up the emulator and before long, Galacticon should look something like this:

7. RecyclerView Working

That’s not all. Tap on the photo, and you should be greeted with a new activity that brings that item into focus:

8. Focus Activity

But that’s still not all! Try rotating your device or emulator (function + control + F11/F12) and you’ll see the image in full screen glory!

9. Landscape focus

Depending on the size of the image and your device screen it may look a little distorted, but don’t worry about that.

Congratulations! You have a working RecyclerView and can take your journey amongst the stars.

Taking A Spacewalk: Adding Scrolling support

If you head back to MainActivity on your device and try to scroll down, you’ll notice something is amiss — your RecyclerView isn’t retrieving any new photos.

10. Scrolling Not Working

Your RecyclerView is doing exactly as it’s told by showing the contents of photosList. The problem is that the app will only retrieve one photo when you load the app. It has no idea when or how to grab more photos.

So next, you’ll retrieve the number of the photos and the last visible photo index while scrolling. Then you’ll check to see if the last photo is visible and if there are no photos already on request. If these are both true, then your app goes and downloads more pretty photos!

This patch will require a spacewalk, so break out your spacesuit and get ready for a zero gravity experience.

In MainActivity.kt, add this property with custom accessor below to MainActivity:

private val lastVisibleItemPosition: Int
  get() = linearLayoutManager.findLastVisibleItemPosition()

This uses your RecyclerView’s LinearLayoutManager to get the index of the last visible item on the screen.

Next, you add a method that inserts an onScrollListener to your RecyclerView, so it can get a callback when the user scrolls:

private fun setRecyclerViewScrollListener() {
  recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
    override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
      super.onScrollStateChanged(recyclerView, newState)
      val totalItemCount = recyclerView!!.layoutManager.itemCount
      if (!imageRequester.isLoadingData && totalItemCount == lastVisibleItemPosition + 1) {

This function gives the RecyclerView a scroll listener that is triggered by scrolling. During scrolling, the listener retrieves the count of the items in its LayoutManager and calculates the last visible photo index. Once done, it compares these numbers (incrementing the index by 1 because the index begins at 0 while the count begins at 1). If they match and there are no photos already on request, then you request a new photo.

Finally, hook everything to the RecyclerView by calling this method from onCreate, just beneath where you set your RecyclerView Adapter:


Hop back in the ship (build and run the app again). Scroll down and you should see quite an improvement!

11. Scrolling Update

Excellent work, your RecyclerView now updates to show the latest photo requested by your app. The great thing is that receivedNewPhoto() handles most of the work because you told it to notify your adapter about new items.

That earns an intergalactic thumbs up for upcycling code!

Layout Changes

Now that your RecyclerView is up and running, it’s time to trick out your spaceship.

Wouldn’t it be cool if your RecyclerView could change its layout? Good news: RecyclerView’s item positioning is separated into a layout manager.

Add a property for a GridLayoutManager to the top of MainActivity.kt:

private lateinit var gridLayoutManager: GridLayoutManager

Note that GridLayoutManager is a built-in layout manager, but it could just as easily be custom.

In onCreate(), initialize the LayoutManager below the existing Linear Layout Manager:

gridLayoutManager = GridLayoutManager(this, 2)

Just like you did with the previous LayoutManager, you pass in the context the manager will appear in, but unlike the former, it takes an integer parameter. In this case, you’re setting the number of columns the grid will have.

Add this method to MainActivity:

private fun changeLayoutManager() {
  if (recyclerView.layoutManager == linearLayoutManager) {
    recyclerView.layoutManager = gridLayoutManager
    if (photosList.size == 1) {
  } else {
    recyclerView.layoutManager = linearLayoutManager

This code checks to see what LayoutManager your RecyclerView is using, and then:

  1. If it’s using the LinearLayoutManager, it swaps in the GridLayoutManager
  2. It requests a new photo if your grid layout only has one photo to show
  3. If it’s using the GridLayoutManager, it swaps in the LinearLayoutManager

Next, you need to make some changes to lastVisibleItemPosition to help it handle the new LayoutManager. Make it look like the following:

private val lastVisibleItemPosition: Int
  get() = if (recyclerView.layoutManager == linearLayoutManager) {
    } else {

Here you ask the RecyclerView to tell you what its LayoutManager is, then you ask that LayoutManager to tell you the position of the last visible item.

To use the grid layout, make use of the Options menu button that is already available in the app. Add the following code underneath onStart():

override fun onOptionsItemSelected(item: MenuItem): Boolean {
  if (item.itemId == {
    return true
  return super.onOptionsItemSelected(item)

This checks the ID of the item tapped in the menu, then works out what to do about it. In this case, there should only be one ID that will match up, effectively telling the app to go away and rearrange the RecyclerView’s LayoutManager.

And just like that, you’re ready to go! Load up the app and tap the button at the top right of the screen, and you’ll begin to see the stars shift:

12. Grid Layout

Star Killer

Sometimes you’ll see things you just don’t like the look of, perhaps a galaxy far, far away that has fallen to the dark side or a planet that is prime for destruction. How could you go about killing it with a swipe?

Luckily, Android engineers have provided a useful class named ItemTouchHelper that gives you easy swipe behavior. Creating and attaching this to a RecyclerView requires just a few lines of code.

In MainActivity.kt, underneath setRecyclerViewScrollListener() add the following method:

private fun setRecyclerViewItemTouchListener() {

  val itemTouchCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
    override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, viewHolder1: RecyclerView.ViewHolder): Boolean {
      return false

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
      val position = viewHolder.adapterPosition

  val itemTouchHelper = ItemTouchHelper(itemTouchCallback)

Let’s go through this step by step:

  1. You create the callback and tell it what events to listen for. It takes two parameters, one for drag directions and one for swipe directions, but you’re only interested in swipe, so you pass 0 to inform the callback not to respond to drag events.
  2. You return false in onMove because you don’t want to perform any special behavior here.
  3. onSwiped is called when you swipe an item in the direction specified in the ItemTouchHelper. Here, you request the viewHolder parameter passed for the position of the item view, then you remove that item from your list of photos. Finally, you inform the RecyclerView adapter that an item has been removed at a specific position.
  4. You initialize the ItemTouchHelper with the callback behavior you defined, and then attach it to the RecyclerView.

Add the method to the activity’s onCreate(), underneath setRecyclerViewScrollListener():


This will attach the ItemTouchListener to the RecyclerView using the code you just wrote.

Run the app once more and swipe across one of your items, you should see it begin to move. If you swipe the item far enough, you should see it animate and vanish. If other items are visible, then they will reorganize themselves to cover the hole. How cool is that?

13 Swipe Away Item

Where To Go From Here?

Nice job! You’ve been on quite an adventure, but now it’s time to head back to Earth and think about what you’ve learned.

  • You’ve created a RecyclerView and all the components it needs, such as a LayoutManager, an Adapter and a ViewHolder.
  • You’ve updated and removed items from an Adapter.
  • You’ve added some cool features like changing layouts and adding swipe functionality.

Above all, you’ve experienced how separation of components — a key attribute of RecyclerViews — provides so much functionality with such ease. If you want your collections to be flexible and provide some excitement, then look no further than the all-powerful RecyclerView.

The final project for this tutorial is available here.

If you want to learn more about RecyclerViews then check out the Android documentation to see what it can do. Take a look at the support library for RecyclerViews to learn how to use it on older devices. If you want to make them fit with the material design spec then check out the list component design specification.

Join us in the forums to discuss this tutorial and your findings as you work with RecylerViews!

Until next time, space traveler!