Recycler View — 2

Vegeedog
Android Studio Notes
3 min readJul 20, 2021

--

Continuing the last article, we are going to improve the layout by using the native android CardView instead of the previous RelativeLayout.

  1. Add CardView dependency

Search for “cardview dependency androidx” (remember the “x”)

And we copy this line of code to our build.gradle (Module)

2. After adding the dependency, we can change our layout file from RelativeLayout to CardView.

In the layout file for our RecyclerView, we use CardView (instead of RelativeLayout) to wrap up.

And we could use some useful properties of the CardView

  • cardElevation: add some 3D style
  • cardCornerRadius: make the corner round-shaped

As for the inner element, we originally have a TextView (txtName), which stands for the name of the contact.

Since we may have other elements inside this RecyclerView, and also, we want to use some functions of RelativeLayout, we put a RelativeLayout in the CardView, and all the other UI elements would be put in this RelativeLayout later on.

The whole layout file code:

3. In our adapter class, we update the ViewHolder class. (since the UI elements have changed)

Then, in onBindViewHolder, since we want to display the contact’s Email address, remember to set the text of the email.

4. Add margins to make the layout less crowded.

  • Add margin between each CardViews.
  • Add margin above name & email

After these modifications, the layout would be like

5. Load images. There are multiple ways to do it.

One way is to use the external library: Glide.

Glide has many functionalities, in which of them is to load images from the Internet.

We search for “glide dependency”, which lead us to the webpage:

bumptech/glide: An image loading and caching library for Android focused on smooth scrolling (github.com)

Add these repositories to build.gradle (Project)

Add these dependencies to build.gradle (Module)

After adding them, remember to click “Sync now

6. Back to the Adapter class. We first update the inner ViewHolder class.

Add ImageView object in the class

Then in the “onBindViewHolder” method, we use the Glide function to load the url and put the image into this ImageView.

7. Since we want to load images from the Internet, we need to add a permission into our manifest file for accessing the Internet.

In the AndroidManifest.xml

Final Layout

--

--