One of the most common UI widgets that have increased in popularity on Android and are the art of Material Design are CardViews. CardViews can be put to good use when combined with RecyclerViews. CardViews extends the FrameLayout and is supported on Android 2.X. In this post I will demonstrate how you can create one for your app.
Let’s begin! Start by creating a new android project with an empty activity.
Add the following dependencies to your build.grade as we require these in order to use the widgets:
NB: Don’t forget to hit that sync now button!
Add the following widget to your activity_main.xml layout:
Next, in your MainActivity.java initialise the RecyclerView in your onCreate method:
CardViews can be used to display anything, in this case I will be using it to display an image and text for a place.
TextView will be used to show the name of the place.
ImageView will be used to show an image of the place - this will be wrapped around a FrameLayout.
Create a new XML layout file for your CardView as follows:
In order to show content on a card, you will need to create a data model for the content you want to display.
Create a java class called Places.java:
Also, create another class called CardAdapter.java. We will be using the view holder design pattern for the adapter. The adapter is a representative of what we want to display on the UI of our app. If we want to display places on our CardView, we need this adapter to do so. This adapter must extend the class RecyclerView.Adapter to implement the ViewHolder pattern.
Let’s go through what this class contains. The items declared in our XML layout in our CardView representing a place, these will need to be initialised to our custom view holder.
Create an array list to store your data. For our case its for our Places class:
Create a few data objects for the data you want to store and display on your CardView as follows:
NB: make sure you have added your images the imagies you will be using to the drawable folder (app -> res -> drawable)
This is to count the number of places in the list.
This is to set the values of your fields of the CardView.
This method is used to initialise your ViewHolder.
If you have followed the tutorial and run your app, you should see something similar to below:
Thanks for reading! If you have any questions, feel free to email or tweet me.