CardView in Android

By Arvind Rai, July 22, 2023
On this page we will learn to use CardView in our Android application.
1. The CardView is a FrameLayout with a rounded corner background and shadow. The CardView can contain ImageView, TextView, RadioGroup etc.
2. To set corner radius, use setRadius() of CardView. In XML we can use app:cardCornerRadius property for this purpose.
3. Cards are drawn with default elevation. To change elevation, use setCardElevation() of CardView. In XML we can use app:cardElevation property for this purpose.
4. To set background color, use setCardBackgroundColor() of CardView. In XML we can use app:cardBackgroundColor property for this purpose.
5. To use CardView in our application, add following dependency in build.gradle.
dependencies {
    implementation "androidx.cardview:cardview:1.0.0"
} 

1. Creating CardView

Find the XML code snippet to create CardView.
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cmCardView"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    android:layout_margin="10dp"
    app:cardCornerRadius="20dp"
    app:cardElevation="10dp"
    app:cardPreventCornerOverlap="true"
    app:cardUseCompatPadding="true"
    app:cardBackgroundColor="@color/cyan”>
    ---------
</androidx.cardview.widget.CardView> 
app:cardCornerRadius : Sets corner radius for card view.
app:cardElevation : Sets elevation.
app:cardPreventCornerOverlap : Boolean value to prevent corner overlap between the card content and rounded corners.
app:cardUseCompatPadding : Boolean value whether to use compact padding.
app:cardBackgroundColor : Sets background color for card view.

The configuration for CardView can be performed programmatically as following.
public class MyViewHolder extends RecyclerView.ViewHolder  {
    public MyViewHolder(View itemView) {
        ---------
        CardView cardView = itemView.findViewById(R.id.cmCardView);
        cardView.setRadius(50f);
        cardView.setCardElevation(50f);
        cardView.setPreventCornerOverlap(true);
        cardView.setUseCompatPadding(true);
       cardView.setCardBackgroundColor(Color.CYAN);
    }
} 
The configuration set programmatically takes precedence over configuration set by XML.

2. Corner Radius

The CardView can make its corner rounded. Find the code to set corner radius.
XML
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cmCardView"
    ---------
    app:cardCornerRadius="20dp">
    ---------
</androidx.cardview.widget.CardView> 
Programmatically
 public class MyViewHolder extends RecyclerView.ViewHolder  {
    public MyViewHolder(View itemView) {
        ---------
        CardView cardView = itemView.findViewById(R.id.cmCardView);
        cardView.setRadius(50f);
    }
} 

3. Elevation

The CardView is created with default elevation. We can change the elevation using following code.
XML
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cmCardView"
    ---------
    app:cardElevation="10dp">
    ---------
</androidx.cardview.widget.CardView> 
Programmatically
public class MyViewHolder extends RecyclerView.ViewHolder  {
    public MyViewHolder(View itemView) {
        ---------
        CardView cardView = itemView.findViewById(R.id.cmCardView);
        cardView.setCardElevation(50f);
    }
} 


4. Background Color

Find the code to set background color for CardView.
XML
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cmCardView"
    ---------
    app:cardBackgroundColor="@color/cyan”>
    ---------
</androidx.cardview.widget.CardView> 
Programmatically
public class MyViewHolder extends RecyclerView.ViewHolder  {
    public MyViewHolder(View itemView) {
        ---------
        CardView cardView = itemView.findViewById(R.id.cmCardView);
        cardView.setCardBackgroundColor(Color.CYAN);
    }
} 

5. CardView with ImageView and TextView

Find the XML file to create CardView with ImageView and TextView.
res/layout/row_item.xml
<?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:id="@+id/cmCardView"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    android:layout_margin="10dp"
    app:cardCornerRadius="20dp"
    app:cardElevation="10dp"
    app:cardBackgroundColor="@color/cyan">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/cmImageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/cmTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="30dp"
            android:textSize="30sp" />
    </LinearLayout>
</androidx.cardview.widget.CardView> 
Find the print screen of the output.
CardView in Android

6. CardView.setOnClickListener()

Find the code to listen click event on CardView.
public class MyViewHolder extends RecyclerView.ViewHolder {
    public MyViewHolder(View itemView) {
        CardView cardView = itemView.findViewById(R.id.cmCardView);
        cardView.setOnClickListener(view ->
        {
            Snackbar.make(cardView.getRootView(), "Clicked.”, Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        });
    }
} 


7. Complete Example using RecyclerView

In our example we are creating a RecyclerView application to display list items. Each item is a CardView containing an image and a text.
The row_item.xml file is already given above in the article. Now find other files.
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.Material3"
        android:fitsSystemWindows="true">

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize" />
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/communication"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout> 
MainActivity.java
package com.cp.app;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import androidx.annotation.ColorInt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.cp.app.databinding.ActivityMainBinding;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;
    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);

        List<MyItem> communications = new ArrayList<>();
        communications.add(new  MyItem("Call", R.drawable.ic_call));
        communications.add(new  MyItem("Chat", R.drawable.ic_chat));
        communications.add(new  MyItem("Comment", R.drawable.ic_comment));
        communications.add(new  MyItem("Duo", R.drawable.ic_duo));
        communications.add(new  MyItem("Email", R.drawable.ic_email));
        communications.add(new  MyItem("Notification", R.drawable.ic_notification));
        communications.add(new  MyItem("Voicemail", R.drawable.ic_voicemail));

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 1);
        RecyclerView recyclerView = findViewById(R.id.communication);
        recyclerView.setLayoutManager(gridLayoutManager);

        adapter = new MyRecyclerViewAdapter(this, communications);
        recyclerView.setAdapter(adapter);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
} 
MyItem.java
package com.cp.app;

public class MyItem {
    private String name;
    private int imageId;

    public MyItem(String name, int imageId) {
        this.name = name;
        this.imageId = imageId;
    }
    public String getName() {
        return name;
    }
    public int getImageId() {
        return imageId;
    }
} 
MyViewHolder.java
package com.cp.app;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.snackbar.Snackbar;

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView myTextView;
    ImageView myImageView;

    public MyViewHolder(View itemView) {
        super(itemView);
        myTextView = itemView.findViewById(R.id.cmTextView);
        myImageView = itemView.findViewById(R.id.cmImageView);
        //card
        CardView cardView = itemView.findViewById(R.id.cmCardView);
        cardView.setCardElevation(50f);
        cardView.setPreventCornerOverlap(true);
        cardView.setUseCompatPadding(true);
        cardView.setOnClickListener(view ->
        {
            Snackbar.make(cardView.getRootView(), "Clicked on " + myTextView.getText(), Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        });
    }
} 
MyRecyclerViewAdapter.java
package com.cp.app;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyViewHolder> {

    private List<MyItem> myList;
    private LayoutInflater layoutInflater;
    public MyRecyclerViewAdapter(Context context, List data) {
        this.layoutInflater = LayoutInflater.from(context);
        this.myList = data;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.row_item, parent, false);
        return new MyViewHolder(view);
    }
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        MyItem item = myList.get(position);
        holder.myImageView.setImageResource(item.getImageId());
        holder.myTextView.setText(item.getName());
    }
    @Override
    public int getItemCount() {
        return myList.size();
    }
} 

8. References

9. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE












©2024 concretepage.com | Privacy Policy | Contact Us