Using CardView and RecyclerView in Android
In this example , we will be developing a Recycler View app.Recycler View is used to display long lists. It is different than other adapters because it reuses Views that were created earlier. This increases app efficiency as a few views are able to display the entire list to the user and reduces system overhead to generate views for all the list items in the list. We will also use a CardView which comes from Material Design of Android. A CardView gives the list item a distinctive look and enhances the overall appearance of the app.
Steps to develop this can be summarized below -
- Make a new project with Empty Activity.
- Name the Launcher Activity as LauncherActivity.class
- Add RecyclerView and CardView Dependencies in gradle - App module
- Create a Button in Launcher Activity that launches the CardViewActivity.class containing recyclerview list
- Create a model class known as DataObject - its objects will be displayed on the list.
- Prepare a layout for RecyclerView byusing RecyclerView Widget.
- Inside the CardViewActivity.class create references for RecyclerView,LayoutManager(Inner Class) and DataObject.
- Define RecylerView object and set an object of RecyclerView.Adapter as an adapter on RecyclerView object using setAdapter()
- Call methods addItem() and deleteItem() on RecyclerViewAdapter object
- Inside onResume method - call OnItemClick() method to detect clicks on Cards.
- You will also have to prepare a method - getDataSet() to get objects of model class.
- Prepare another class named as RecyclerViewActivity which extends RecyclerView.Adapter
- Prepare a layout card_view to display items inside the CardView
- RecyclerViewActivity class is responsible for calling all the relevant methods while RecyclerView is being used.
Used Concepts & Used Version:
- compileSdkVersion 25
- buildToolsVersion "25.0.0"
-
'com.android.support:cardview-v7:22.0.0'
- 'com.android.support:recyclerview-v7:22.0.0'
- 'com.android.support:design:23.0.1'
Now, let us begin the development...
1.LauncherActivity.class (Launcher Activity)
This Activity has only one button which when clicked will take the user to CardViewActivity.class
2. Layout for LauncherActivity.class
3.CardViewActivity.class
activity_card_view.xml
RecyclerViewActivity.class
card_view.xml
DataObejct.class
Output