Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

49. An Android RecyclerView and CardView Tutorial

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 messages to be displayed to the user indicating which card was tapped.

49.1 Creating the CardDemo Project

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Basic Activity template before clicking on the Next button.

Enter CardDemo into the Name field and specify com.ebookfrenzy.carddemo as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java.

Modifying the Basic Activity Project

Since the Basic Activity was selected, the layout includes a floating action button which is not required for this project. Load the activity_main.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 MainActivity.java file and remove the floating action button code from the onCreate method as follows:

@Override

protected void onCreate(Bundle savedInstanceState) {

   ...

49.2 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 androidx.cardview.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 Code mode and modify the layout so that it reads as follows:

<?xml version="1.0" encoding="utf-8"?>

<androidx.cardview.widget.CardView

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height...

49.3 Adding the RecyclerView

Select the content_main.xml layout file and drag and drop a RecyclerView object from the Containers section of the palette onto the layout so that it is positioned in the center of the screen where it should automatically resize to fill the entire screen. Use the Infer constraints toolbar button to add any missing layout constraints to the view. Using the Attributes tool window, change the ID of the RecyclerView instance to recyclerView and the layout_width and layout_height properties to match_constraint.

49.4 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:

https://www.ebookfrenzy.com/retail/androidstudio41/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:

Figure 49-1

49.5 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 -> Java Class menu option. In the new class dialog, enter RecyclerAdapter into the Name field and select Class from the list before tapping the Return keyboard key to create the new Java class file.

Edit the new RecyclerAdapter.java 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.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ImageView...

49.6 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 MainActivity.java file and modify the onCreate() method to implement this initialization code:

package com.ebookfrenzy.carddemo;

.

.

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.widget.Toolbar;

import androidx.recyclerview.widget.LinearLayoutManager;

import androidx.recyclerview.widget.RecyclerView;

 

import android.view.View;

import android.view.Menu;

import android.view.MenuItem;

 

public class MainActivity...

49.7 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:

Figure 49-2

49.8 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.java file and modify the ViewHolder class declaration so that it reads as follows:

.

.

import com.google.android.material.snackbar.Snackbar;

.

.

class ViewHolder extends RecyclerView.ViewHolder{

 

    ImageView itemImage;

    TextView itemTitle;

    TextView itemDetail;

 

    ViewHolder(View itemView) {

        super(itemView);

        itemImage = itemView.findViewById...

49.9 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.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth