Android's RecyclerView and CardView widgets

  • Written by  Clive

RecyclerView and CardView widgets for all

RecyclerView and CardView tutorial icon

Android’s latest release, Lollipop (Android 5.0 API Level 21) includes the new RecyclerView and CardView widgets. They’re also made available for use on devices running API Level 7 and above through the Support Libraries.

The RecyclerView provides a more advanced and flexible way of displaying lists than the old ListView.

The CardView widget enables you to display views inside a card. You can design the card so that its look is consistent across your app.

Displaying Lists

The RecyclerView widget is essentially a container that you can use to display large sets of data. It’s very efficient as it only displays a few items at a time. Views that are no longer needed are recycled and reused. Not having to keep on inflating views saves CPU resources and valuable memory is saved by not having to keep views alive in the background.

Using the RecyclerView widget is easy

It’s easy to use the RecyclerView Widget, simply:

  • Specify an adapter – you need to create a custom adapter by extending the RecyclerView.Adapter class. The adapter will then display the data in the views that it creates
  • Specify a layout manager – you’ll need a layout manager to manage the positioning of items within the RecyclerView widget and also for recycling the views. There are three built-in layout managers:
    • LinearLayoutManager – where items appear in a vertical or horizontal scrolling list
    • GridLayoutManager - where items appear in a grid
    • StaggeredGridLayoutManager – where items appear in a staggered grid

You can also create your own custom layout manager.

Animate the items

You can animate the list items when they are added to or removed from the list. Adding and removing items are set by default to use the default animation. You can also use your own custom animations.

CardView widgets

Use the CardView widget to create cards that will look the same wherever you use them in your apps.

You can specify their background, whether their corners should be rounded and if they should have a shadow.

We’ll use both the CardView and RecyclerView widgets in our tutorial app.

Our CardView and RecyclerView tutorial

Our app displays a number of cards containing a name, email address and an image. The cards are in a scrollable list.

Selecting a card removes it from the list. Pressing the Action button in the Action Bar adds a removed card back into the list.

Android RecyclerView and CardView widgets tutorial screenshot

We display our list of items using the RecyclerView widget. Each item is displayed inside a CardView card. Selecting Sally removes that card from the list and the remaining cards move up

Android RecyclerView and CardView widgets tutorial screenshot 2

Pressing the Add item action button, moves the cards down to make space for adding a previously removed card

So how’s it done?

First things first

Our minimum SDK is 10 (Gingerbread_MR1) so we need to use the Support Libraries to:

  • Use the ActionBar
  • Use the CardView widget
  • Use the RecyclerView widget

In Android Studio, check your app’s build.gradle file, making sure that it includes the appropriate dependencies:

Android RecyclerView and CardView widgets tutorial bulid.gradle dependencies

Include the support libraries for the AppCompat theme, CardView and RecyclerView classes in your build.gradle file

Use an ActionBar

We want to show a menu action item on the ActionBar so make sure that you’re using the AppCompat theme and that your activity extends the ActionBarActivity class.

You can read all about using the ActionBar in our ActionBar tutorial, Using Android’s Action Bar

Put each item’s data in a CardView widget

The CardView widget lets you display data consistently across your app.

Android CardView widgets tutorial

We use the CardView widget to display each of the list items. You can set the CardView’s attributes to control the look of the card

Define the CardView in an XML layout file

We define the CardView widget in its own xml layout resource file, cards_layout.xml.

Here’s the code:

Android CardView widgets tutorial CardView

Define the CardView widget’s look in an XML layout file

A quick explanation

We set the width of the card to match its parent so that the card stretches across the width of the screen. The height is set so that it stretches to enclose its biggest view, the icon.

We set the background colour using a colour resource. The cardCornerRadius attribute sets the radius of each of the card’s corners.

The cardElevation attribute provides the shadow.

In addition, we include the text views and the image view within the CardView widget’s tags (see the project code).

Put the card views in the RecyclerView widget

Define the RecyclerView widget in an XML layout file

The RecyclerView widget is like a ListView. It displays a scrollable list of items, which in this case, are cards.

We define our RecyclerView widget in the activity’s layout file, activity_main.xml:

Android RecyclerView widget tutorial

Here’s a basic RecyclerView layout

A quick explanation

Specify the width and height for the RecyclerView widget. We set ours to fill the screen by using the match_parent constant.

The scrollbars attribute displays a vertical scrollbar on the side of the screen.

Put it all together in the activity’s onCreate() method

We set up the recycler view in the activity’s onCreate() method. We also create our data lists and set up the recycler view’s adapter here.

Here’s the code:

Android RecyclerView widget tutorial onCreate() set up

Prepare your RecyclerView widget in the activity’s onCreate() method

A quick explanation

We create an instance of our inner class MyOnClickListener interface, myOnClickListener. We’ll use it to remove selected items.

Next, we get a reference to our RecyclerView widget, recyclerView.

Then we set the setHasFixedSize() method to true. This increases performance because the recycler view will know in advance that it can’t change the size of the recycler view, even if the size of the adapter changes.

We create a new linear layout manager for our recycler view. We also specify that we want to use the default animation for the removal and addition of items. You could leave this out as the animation is included by default. However, this is how you would set your recycler view to use an animation.

Next, we create a new ArrayList, people and populate it with our data (which can be found in the MyData class). Essentially we have a number of arrays:

  • nameArray – which contains 10 names
  • emailArray – which contains 10 email addresses
  • drawableArray – which contains 10 drawable id’s
  • id_ - which contains 10 id’s

We also create an ArrayList, removedIems. We’ll populate it with the id’s of items that are removed from the displayed list. We can then access the list to get the id of an item that we want to add to the list. We then use the id to get the item’s details.

Lastly we create a new instance of our custom adapter and set it to our recycler view.

The Listener interface

We include a listener, MyOnClickListener as an inner class. The listener is attached to the RecyclerView widget’s views in the adapter’s onCreateViewHolder() method.

Removing items from the list

The listener’s onClick() method is triggered when any of the displayed items are clicked. We include a call to the removeItem() method to remove the selected item from the list.

Here’s the code for the removeItem() method:

Android RecyclerView widget tutorial remove item notifyItemRemoved()

The removeItem() method receives the selected view as a parameter and then removes it from the list

A quick explanation

We get the position of the selected view in the list. Then we get an instance of the view holder, which enables us to get a reference to the name text view that it contains. Next we get the text displayed in this text view and then loop through our names array to find it’s matching ID.

We then add the selected item’s ID to our list of removed items, remove the item from people’s list and notify the adapter that this item has been removed (so that the displayed list can be updated).

Adding items to the list

We can add the removed items back to the list.

Pressing the Add Item action button triggers the onOptionsItemSelected() method. This is where we call the addRemovedItemToList() method which adds the removed items back into the list, one-at-a-time.

Here’s the code for the addRemovedItemToList():

Android RecyclerView widget tutorial add item notifyItemInserted()

The addRemovedItemToList() method adds the removed item back into the people list and also notifies the adapter of the addition so that it can update the displayed list

A quick explanation

We create the variable, addItemAtListPosition which we give a value of 3. We use it as the index when we insert the item into the people array list. The item will be inserted at the index position in the array list, which is 3 in this case.

We use the first id stored in the removedItems array list as the index to get the data out of our MyData arrays.

After the people array list has been updated, we call notifyItemInserted() to notify the adapter that we have added an item and that it should update the displayed list.

Finally we remove the added item’s ID from the removedItems array list.

Update: An error occurs when you try to add an item to the list if there are less than three items in the list. Replace the int addItemAtListPosition = 3; line with the following code:

Android. Updating recyclerview list

Add this code to fix the error that occurs when you try to add a removed item to a list shorter than 3 items

Animating the items as they are removed and added to the list

Animation is implemented by default to animate views when they are removed and added to the list.

You can also use you own custom animations. We use the default animations.

Removing an item slides the next one up. Adding an item makes space by sliding an item down. The new item is then placed in the space.

For the animations to work, you have to use the following methods when adding or removing items:

  • notifyItemRemoved() – when removing items
  • notifyItemInserted() – when adding items

Note: Unconfirmed, that the animation only works on JellyBean and above.

The Adapter

The adapter provides access to our data. It also provides the views for the items. We create our custom recycler adapter by extending the RecyclerView.Adapter class.

There are three methods that you must implement:

  • onCreateViewHolder () – creates a new ViewHolder to contain our text and image
  • onBindViewHolder() – displays our text and image at the specified position in the list
  • getItemCount() – gets the number of items in the adapter

The ViewHolder

We declare a view holder subclass within our adapter.

Here’s the constructor for our ViewHolder:

Android RecyclerView widget tutorial viewHolder

ViewHolder constructor

A quick explanation

Our view holder will contain our text views and the image. We’re able to access these views via the view holder.

Creating the ViewHolder

A new ViewHolder is created when the RecyclerView calls onCreateViewHolder():

Use onCreateViewHolder() create the viewHolder

onCreateViewHolder() creates a reusable ViewHolder

A quick explanation

We inflate the cards layout and set the listener to listen for when this view is clicked. The ViewHolder contains all the views for one item. The view holder is returned to be placed in the displayed list by the layout manager.

The LayoutManager

The LayoutManager manages the positioning of the items in the scrollable list as well as the recycling of the views.

There are three built-in layout managers:

  • LinearLayoutManager – where items appear in a vertical or horizontal scrolling list
  • GridLayoutManager - where items appear in a grid
  • StaggeredGridLayoutManager – where items appear in a staggered grid

You can also create your own. We use the default LinearLayoutManager.

Displaying the items using onBindViewHolder()

The RecyclerView calls onBindViewHolder() to display an item: 

Use onBindViewHolder() to display the data

Use onBindViewHolder() to display the data 

A quick explanation

We get references to our text views and image view currently contained by this instance of the view holder. We then use this items position in the displayed list as an index to retrieve name, email address and image id from our data set.

The data is then displayed.


Check out Grokking Android’s blog post on RecyclerView’s

I hope that you have found this tutorial helpful.

This project was created using Android Studio.

You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.

Want to learn how to harness the power of third-party Api’s like Twitter, Youtube, Flickr, Imgur and thousands more? You can build the functionality of these apps directly into your apps, accessing their data, making your apps leap ahead of the competition.

We’ve prepared a tutorial app that uses Imgur’s  (an image repository) api’s to search its database, retrieve some images and display them in a RecyclerView.api's, OkHttp, Http, Picasso, RecyclerView, ebook

We also briefly introduce you to Http, OkHttp, Api’s, Json and Picasso making it easy to understand as we work through the tutorial.

Check out our eBook package, Let your apps take a giant leap.