Cardview with Recyclerview Android Example [beginners]

Ultimate Guide To Material Cardview with Recyclerview In Android

Cardview Android is a new widget for Android, which can be used to display a card sort of layout in android. Cardview was introduced in Material Design in API level 21 (Android 5.0 i.e Lollipop).

Since Cardview is part of material design. It’s such a view that has all material design properties, most importantly showing shadows according to the elevation.

The best part about this view is that it extends FrameLayout and it can be displayed on all the platforms of Android since it’s available through the Support v7 library.

The design of the cardview will be looks like this,

In the above picture, every box is made with cardview in android.

Before jumping into the coding part, Let’s see the Cardview XML attribute, that makes the cardview looks beautiful.

Cardview XML attribute

CardView_cardBackgroundColor : ColorStateList: The new ColorStateList to set for the card background

CardView_cardCornerRadius : float: The radius in pixels of the corners of the rectangle shape

CardView_cardElevation : float: The backward compatible elevation in pixels.

CardView_cardMaxElevation : float: The backward-compatible maximum elevation in pixels.

CardView_cardPreventCornerOverlap : boolean: Whether CardView should add extra padding to content to avoid overlaps with the CardView corners.

CardView_cardUseCompatPadding : boolean: true> if CardView should add padding for the shadows on platforms Lollipop and above.

CardView_contentPadding Sets the padding between the Card’s edges and the children of CardView.

CardView_contentPaddingBottom : int: The bottom padding in pixels

CardView_contentPaddingLeft : int: The left padding in pixels

CardView_contentPaddingRight : int: The right padding in pixels

Done with an explanation about the android cardview. Let’s get into the coding part.

Cardview android example with Recyclerview

In this post, I am going to create a cardview with recyclerview in android to list the movies with the image and the movie title.

example application demo,

Step 1 — Adding dependencies

In this example, I am using recyclerview with cardview. But I am not going deeper into recyclerview. I already have a post on recyclerview in android.

Recyclerview Android Example [Beginners] – Howtodoandroid

implementation "androidx.cardview:cardview:1.0.0" implementation 'androidx.recyclerview:recyclerview:1.1.0'
Code language: JavaScript (javascript)

Step 2 — Prepare data for the recyclerview

To prepare data, we mostly use Retrofit to fetch data from the REST API. I have explained retrofit in another post.

Retrofit Android Example With Recyclerview – Howtodoandroid

In this example, I am using hard-coded data.

Create a model class for the Movies. So, my Movie.kt.

data class Movie(var title: String, var image: Int, var rating: Float)

In your MainActivity.ktcreate movie list items.

private fun prepareMovie() { var movie = Movie("Star Wars The Last Jedi", R.drawable.star_war, 8.0F) movieList.add(movie) movie = Movie("Coco", R.drawable.coco,8.3F) movieList.add(movie) movie = Movie("Justice League", R.drawable.justice_league,9.0F) movieList.add(movie) movie = Movie("Thor: Ragnarok", R.drawable.thor_ragnarok, 8.5F) movieList.add(movie) movie = Movie("Star Wars The Last Jedi", R.drawable.star_war, 8.4F) movieList.add(movie) movie = Movie("Coco", R.drawable.coco,8.2F) movieList.add(movie) movie = Movie("Justice League", R.drawable.justice_league,8.4F) movieList.add(movie) movie = Movie("Thor: Ragnarok", R.drawable.thor_ragnarok, 8.9F) movieList.add(movie) }
Code language: PHP (php)

3. Create a recyclerview adapter with a cardview layout

the adapter needs to be created to list all the movies in the recyclerview. So, we are going to create an adapter layout with cardview.

recyclerview_adapter_layout.xml

<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:cardView="http://schemas.android.com/apk/res-auto" android:id="@+id/carView" android:layout_width="match_parent" android:layout_height="90dp" cardView:cardCornerRadius="8dp" cardView:cardElevation="8dp" android:layout_margin="8dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image" android:scaleType="centerCrop" tools:background="@tools:sample/backgrounds/scenic" android:layout_width="90dp" android:layout_height="90dp" cardView:layout_constraintStart_toStartOf="parent" cardView:layout_constraintTop_toTopOf="parent"/> <TextView android:id="@+id/title" android:layout_width="0dp" android:layout_height="wrap_content" android:fontFamily="sans-serif-smallcaps" android:gravity="center_vertical" android:layout_margin="8dp" cardView:layout_constraintTop_toTopOf="parent" cardView:layout_constraintLeft_toRightOf="@id/image" cardView:layout_constraintRight_toRightOf="parent" android:lines="1" android:padding="5dp" android:textStyle="bold" tools:text="@tools:sample/full_names" android:textAppearance="@style/TextAppearance.AppCompat.Title" android:textColor="@android:color/black" /> <androidx.appcompat.widget.AppCompatTextView android:id="@+id/textRating" android:layout_width="0dp" android:layout_height="wrap_content" cardView:layout_constraintTop_toBottomOf="@id/title" cardView:layout_constraintStart_toStartOf="@id/title" tools:text="Rating : 9.5" android:layout_marginTop="4dp" android:textAppearance="@style/TextAppearance.AppCompat.Body1"/> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.cardview.widget.CardView>
Code language: HTML, XML (xml)

in the cardview layout,

I am using cardView:cardCornerRadius to set the radius for the cardview.

Also, use cardView:cardElevation it for the shadow outside the cardview.

the cardview UI looks like,

cardview item design

now, the UI for the recyclerview adapter is ready. Next, create an adapter and inflate the cardview layout into a recyclerview adapter.

RecyclerViewAdapter.kt

class RecyclerViewAdapter constructor(private val movieList: List<Movie>) : RecyclerView.Adapter<MyViewHolder>() { private var clickListener: ClickListener<Movie>? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.recyclerview_adapter_layout, parent, false) return MyViewHolder(view) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val movie = movieList[position] holder.title.text = movie.title holder.image.setBackgroundResource(movie.image) holder.rating.text = "Rating : ${movie.rating}" } override fun getItemCount(): Int { return movieList.size } inner class MyViewHolder(itemView: View) : ViewHolder(itemView) { val title: TextView = itemView.findViewById(R.id.title) val image: ImageView = itemView.findViewById(R.id.image) val cardView: CardView = itemView.findViewById(R.id.carView) val rating: TextView = itemView.findViewById(R.id.textRating) } }
Code language: HTML, XML (xml)

Step 4 — setup recyclerview with adapter

Already, we prepare data and an adapter. Now, we going to set up the data into recyclerview by using the adapter.

movieList = ArrayList() recyclerView = findViewById<View>(R.id.recyclerView) as RecyclerView recyclerViewAdapter = RecyclerViewAdapter(movieList) val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this) recyclerView!!.layoutManager = layoutManager recyclerView!!.adapter = recyclerViewAdapter
Code language: JavaScript (javascript)

Done with the coding part. Now if you run the code the output will be like this,

Bonus

setup click listener for cardview in android

to set click listener in cardview. First,

1. Create a click listener interface.

interface ClickListener<T> { fun onItemClick(data: T) }
Code language: PHP (php)

2. in the recyclerview adapter, create a clickListener instance and also create the setOnItemClickListener method to attach the click listener to mainActivity.

fun setOnItemClickListener(movieClickListener: ClickListener<Movie>?) { clickListener = movieClickListener }
Code language: HTML, XML (xml)

3. implement a click listener for cardview and call the onItemClick method.

holder.cardView.setOnClickListener { clickListener!!.onItemClick(movie) }

4. Finally, In your mainActivity pass the clickListener implementation to the recyclerview adapter.

recyclerViewAdapter!!.setOnItemClickListener(object : ClickListener<Movie> { override fun onItemClick(data: Movie) { Toast.makeText(this@MainActivity, data.title, Toast.LENGTH_SHORT).show() } })
Code language: HTML, XML (xml)

That’s it. we successfully created the cardview with recyclerview. also, implemented the click listener for the cardview.

You can download the cardview android example on Github.

Android-Example/CardViewAndroidKotlin at master · velmurugan-murugesan/Android-Example (github.com)

Check out my other post,

Android capture image from the camera programmatically

Implementing Pull To Refresh In Android

Popupwindow Android example in Kotlin

Conclusion

Thanks for reading. Nowadays, Cardview is an important component in android. So, try this example and let me know your feedback in the comments.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *