Android CardView with RecyclerView

Android CardView with RecyclerView

In the previous article, we learned to you about Android RecyclerView. Now in this article, we are going to learn Android CardView with RecyclerView.CardView is the new control introduced in v7 Support Library. Its a FrameLayout with shadow, corner radius and elevation property after Android Lollipop.

CardView is mostly used for good looking UI with RecyclerView. Here we are using CardView in our previous article?s UI. We are going to our previous article sample code. Let?s start.

First open build.gradle file from app level and add a dependency for CardView: com.android.support:cardview-v7:27.0.2 and sync the project.

Change item_row.xml layout as below:

<?xml version=”1.0″ encoding=”utf-8″?><android.support.v7.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=”wrap_content”android:layout_margin=”8dp”app:cardCornerRadius=”6dp”app:cardElevation=”6dp”><LinearLayoutandroid:layout_width=”match_parent”android:layout_height=”wrap_content”android:padding=”8dp”android:orientation=”vertical”><TextViewandroid:id=”@+id/txtName”android:layout_width=”match_parent”android:layout_height=”wrap_content”android:padding=”1dp”android:textColor=”@color/black”android:textSize=”18sp” /><TextViewandroid:id=”@+id/txtDistance”android:layout_width=”match_parent”android:layout_height=”wrap_content”android:padding=”1dp”android:textColor=”@color/black” /><TextViewandroid:id=”@+id/txtGravity”android:layout_width=”match_parent”android:layout_height=”wrap_content”android:padding=”1dp”android:textColor=”@color/black” /><TextViewandroid:id=”@+id/txtDiameter”android:layout_width=”match_parent”android:layout_height=”wrap_content”android:padding=”1dp”android:textColor=”@color/black” /></LinearLayout></android.support.v7.widget.CardView>

Remove this line from activity to remove divider between row. Because CardView has its own effect (we say elevation) for separation of two rows in RecyclerView.

recyclerView.addItemDecoration(new LineDividerItemDecoration(this, R.drawable.line_divider))

Remove RecyclerView background color (blue) from activity_main.xml

Now run the project and you can see below output:

Image for postAndroid CardView with RecyclerView

Now we are going to make it more good looking with colours. Use app:cardBackgroundColor=?@color/light_blue? for change background colour of CardView. Use the only cardBackgroundColor, do not use backgroundColor.

Find source here.

More examples of CardView with RecyclerView are below:

Image for postImage for postImage for postImage for post

22