Difference between revisions of "A Kotlin Android RecyclerView and CardView Tutorial"
(Created page with "In this chapter an example project will be created that makes use of both the CardView and RecyclerView components to create a scrollable list of cards. The completed app will...") |
(No difference)
|
Revision as of 17:43, 27 November 2017
In this chapter an example project will be created that makes use of both the CardView and RecyclerView components to create a scrollable list of cards. The completed app will display a list of cards containing images and text. In addition to displaying the list of cards, the project will be implemented such that selecting a card causes a messages to be displayed to the user indicating which card was tapped.
Creating the CardDemo Project
Create a new project in Android Studio, entering CardDemo into the Application name field and ebookfrenzy.com as the Company Domain setting before clicking on the Next button.
On the form factors screen, enable the Phone and Tablet option and set the minimum SDK setting to API 14: Android 4.0 (IceCreamSandwich) and continue to proceed through the screens.
In the next chapter, the scroll handling features of the AppBar, Toolbar and CoordinatorLayout layout will be demonstrated using this project. On the activity selection screen, therefore, request the creation of a Basic Activity named CardDemoActivity with a corresponding layout file named activity_card_demo. Click on the Finish button to initiate the project creation process.
Once the project has been created, load the content_card_demo.xml file into the Layout Editor tool and select and delete the “Hello World” TextView object.
Removing the Floating Action Button
Since the Basic Activity was selected, the layout includes a floating action button which is not required for this project. Load the activity_card_demo.xml layout file into the Layout Editor tool, select the floating action button and tap the keyboard delete key to remove the object from the layout. Edit the CardDemoActivity.kt file and remove the floating action button code from the onCreate method as follows:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_card_demo) setSupportActionBar(toolbar) fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } }
Adding the RecyclerView and CardView Libraries
Within the Project tool window locate and select the module level build.gradle file and modify the dependencies section of the file to add the support library dependencies for the RecyclerView and CardView:
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' implementation 'com.android.support:design:26.1.0' implementation 'com.android.support:recyclerview-v7:26.1.0' implementation 'com.android.support:cardview-v7:26.1.0' . . }
When prompted to do so, resync the new Gradle build configuration by clicking on the Sync Now link in the warning bar.
Designing the CardView Layout
The layout of the views contained within the cards will be defined within a separate XML layout file. Within the Project tool window right click on the app -> res -> layout entry and select the New -> Layout resource file menu option. In the New Resource Dialog enter card_layout into the File name: field and android.support.v7.widget.CardView into the root element field before clicking on the OK button.
Load the card_layout.xml file into the Layout Editor tool, switch to Text mode and modify the layout so that it reads as follows:
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/card_view" android:layout_margin="5dp" card_view:cardBackgroundColor="#81C784" card_view:cardCornerRadius="12dp" card_view:cardElevation="3dp" card_view:contentPadding="4dp" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" > <ImageView android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/item_image" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginEnd="16dp" android:layout_marginRight="16dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_title" android:layout_toEndOf="@+id/item_image" android:layout_toRightOf="@+id/item_image" android:layout_alignParentTop="true" android:textSize="30sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_detail" android:layout_toEndOf="@+id/item_image" android:layout_toRightOf="@+id/item_image" android:layout_below="@+id/item_title" /> </RelativeLayout> </android.support.v7.widget.CardView>
Adding the RecyclerView
Select the activity_card_demo.xml layout file and modify it to add the RecyclerView component immediately before the AppBarLayout:
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:contextcom.ebookfrenzy.carddemo.CardDemoActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <android.support.design.widget.AppBarLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay"> . . .
Creating the RecyclerView Adapter
As outlined in the previous chapter, the RecyclerView needs to have an adapter to handle the creation of the list items. Add this new class to the project by right-clicking on the app -> java -> com.ebookfrenzy.carddemo entry in the Project tool window and selecting the New -> Kotlin File/Class menu option. In the Create New Class dialog, enter RecyclerAdapter into the Name: field before clicking on the OK button to create the new Kotlin class file.
Edit the new RecyclerAdapter.kt file to add some import directives and to declare that the class now extends RecyclerView.Adapter. Rather than create a separate class to provide the data to be displayed, some basic arrays will also be added to the adapter to act as the data for the app:
package com.ebookfrenzy.carddemo import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView class RecyclerAdapter : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() { private val titles = arrayOf("Chapter One", "Chapter Two", "Chapter Three", "Chapter Four", "Chapter Five", "Chapter Six", "Chapter Seven", "Chapter Eight") private val details = arrayOf("Item one details", "Item two details", "Item three details", "Item four details", "Item file details", "Item six details", "Item seven details", "Item eight details") private val images = intArrayOf(R.drawable.android_image_1, R.drawable.android_image_2, R.drawable.android_image_3, R.drawable.android_image_4, R.drawable.android_image_5, R.drawable.android_image_6, R.drawable.android_image_7, R.drawable.android_image_8) }
Within the RecyclerAdapter class we now need our own implementation of the ViewHolder class configured to reference the view elements in the card_layout.xml file. Remaining within the RecyclerAdapter.kt file implement this class as follows:
. . class RecyclerAdapter : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() { . . inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var itemImage: ImageView var itemTitle: TextView var itemDetail: TextView init { itemImage = itemView.findViewById(R.id.item_image) itemTitle = itemView.findViewById(R.id.item_title) itemDetail = itemView.findViewById(R.id.item_detail) } } . . }
The ViewHolder class contains an ImageView and two TextView variables together with a constructor method that initializes those variables with references to the three view items in the card_layout.xml file.
The next item to be added to the RecyclerAdapter.kt file is the implementation of the onCreateViewHolder() method:
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder { val v = LayoutInflater.from(viewGroup.context) .inflate(R.layout.card_layout, viewGroup, false) return ViewHolder(v) }
This method will be called by the RecyclerView to obtain a ViewHolder object. It inflates the view hierarchy card_layout.xml file and creates an instance of our ViewHolder class initialized with the view hierarchy before returning it to the RecyclerView.
The purpose of the onBindViewHolder() method is to populate the view hierarchy within the ViewHolder object with the data to be displayed. It is passed the ViewHolder object and an integer value indicating the list item that is to be displayed. This method should now be added, using the item number as an index into the data arrays. This data is then displayed on the layout views using the references created in the constructor method of the ViewHolder class:
override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) { viewHolder.itemTitle.text = titles[i] viewHolder.itemDetail.text = details[i] viewHolder.itemImage.setImageResource(images[i]) }
The final requirement for the adapter class is an implementation of the getItem() method which, in this case, simply returns the number of items in the titles array:
override fun getItemCount(): Int { return titles.size }
Adding the Image Files
In addition to the two TextViews, the card layout also contains an ImageView on which the Recycler adapter has been configured to display images. Before the project can be tested these images must be added. The images that will be used for the project are named android_image_<n>.jpg and can be found in the project_icons folder of the sample code download available from the following URL:
http://www.ebookfrenzy.com/web/as30kotlin/index.php
Locate these images in the file system navigator for your operating system and select and copy the eight images. Right click on the app -> res -> drawable entry in the Project tool window and select Paste to add the files to the folder:
[[File:]]
Initializing the RecyclerView Component
At this point the project consists of a RecyclerView instance, an XML layout file for the CardView instances and an adapter for the RecyclerView. The last step before testing the progress so far is to initialize the RecyclerView with a layout manager, create an instance of the adapter and assign that instance to the RecyclerView object. For the purposes of this example, the RecyclerView will be configured to use the LinearLayoutManager layout option. Edit the CardDemoActivity.kt file and modify the onCreate() method to implement this initialization code:
package com.ebookfrenzy.carddemo import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.activity_card_demo.* import android.support.v7.widget.RecyclerView import android.support.v7.widget.LinearLayoutManager class CardDemoActivity : AppCompatActivity() { private var layoutManager: RecyclerView.LayoutManager? = null private var adapter: RecyclerView.Adapter<RecyclerAdapter.ViewHolder>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_card_demo) setSupportActionBar(toolbar) layoutManager = LinearLayoutManager(this) recycler_view.layoutManager = layoutManager adapter = RecyclerAdapter() recycler_view.adapter = adapter } . . }
Testing the Application
Compile and run the app on a physical device or emulator session and scroll through the different card items in the list:
[[File:]]
Responding to Card Selections
The last phase of this project is to make the cards in the list selectable so that clicking on a card triggers an event within the app. For this example, the cards will be configured to present a message on the display when tapped by the user. To respond to clicks, the ViewHolder class needs to be modified to assign an onClickListener on each item view. Edit the RecyclerAdapter.kt file and modify the ViewHolder class declaration so that it reads as follows:
. . import android.support.design.widget.Snackbar . . inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var itemImage: ImageView var itemTitle: TextView var itemDetail: TextView init { itemImage = itemView.findViewById(R.id.item_image) itemTitle = itemView.findViewById(R.id.item_title) itemDetail = itemView.findViewById(R.id.item_detail) itemView.setOnClickListener { v: View -> } } } . . }
Within the body of the onClick handler, code can now be added to display a message indicating that the card has been clicked. Given that the actions performed as a result of a click will likely depend on which card was tapped it is also important to identify the selected card. This information can be obtained via a call to the getAdapterPosition() method of the RecyclerView.ViewHolder class. Remaining within the RecyclerAdapter.kt file, add code to the onClick handler so it reads as follows:
itemView.setOnClickListener { v: View -> var position: Int = getAdapterPosition() Snackbar.make(v, "Click detected on item $position", Snackbar.LENGTH_LONG).setAction("Action", null).show() }
The last task is to enable the material design ripple effect that appears when items are tapped within Android applications. This simply involves the addition of some properties to the declaration of the CardView instance in the card_layout.xml file as follows:
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/card_view" android:layout_margin="5dp" card_view:cardBackgroundColor="#81C784" card_view:cardCornerRadius="12dp" card_view:cardElevation="3dp" card_view:contentPadding="4dp" android:foreground="?selectableItemBackground" android:clickable="true" >
Run the app once again and verify that tapping a card in the list triggers both the standard ripple effect at the point of contact and the appearance of a Snackbar reporting the number of the selected item.
Summary
This chapter has worked through the steps involved in combining the CardView and RecyclerView components to display a scrollable list of card based items. The example also covered the detection of clicks on list items, including the identification of the selected item and the enabling of the ripple effect visual feedback on the tapped CardView instance.