Android CardView Example

The CardView UI component shows information inside cards. It is essentially a FrameLayout with rounded corners and shadow based on its elevation. CardView wraps a layout and will often be the container used in a layout for each item within a ListView or RecyclerView.

In this project, we will be using CardView within the RecyclerView and ListAdapter to display a contact List. The contact list consists of each card containing Name and contact.

Screenshots

Android CardView Example

Create an android project using android studio and follow below steps to get the sample code working.

Changes in layout file

Step 1 : Create a RecyclerView in the activity_main.xml file as follows to hold cards we will be creating:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/contactsRecyclerViewID"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"
    android:orientation="vertical"
    android:background="#00f"
    tools:context=".MainActivity">

</android.support.v7.widget.RecyclerView>

Step 2 : Create the CardView Layout to hold the information to be present in cards as follows. Name the file as list_item.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/contactLayoutID"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginHorizontal="10dp"
    android:layout_marginVertical="5dp"
    android:orientation="vertical">

<android.support.v7.widget.CardView
    android:id="@+id/contactCardID"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:cardBackgroundColor="#BFFFFF"
    app:cardCornerRadius="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <TextView
        android:id="@+id/nameTxtID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Ross"
        android:textSize="25dp"
        android:textColor="#000"
        android:layout_marginStart="10dp"
        />

    <TextView
        android:id="@+id/contactTxtID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="9834629048"
        android:textSize="20dp"
        android:textColor="#000"
        android:textAlignment="textEnd"
        android:layout_marginEnd="30dp"
        android:layout_marginBottom="5dp"
        android:layout_below="@id/nameTxtID"/>

    </LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

Adding Dependencies for RecyclerView and CardView

Step 3 : Add the following dependencies in the build.gradle file if error persists :

//  To add recyclerView dependency
    //  1. check your compileSdkVersion
    //  2. Replace 'compileSdkVersion' from below line and uncomment it
    //  implementation 
    //   "com.android.support:recyclerview-v7:compileSdkVersion.0.0"
// In case you don't know compileSdkVersion just add implementation 
    //  "com.android.support:recyclerview-v7:+"

    implementation "com.android.support:recyclerview-v7:28.0.0"
    implementation 'com.android.support:cardview-v7:28.0.0'

Changes in Activity file

Step 4 : Update the MainActivity File to initialize the RecyclerView and List of contacts cards.

public class MainActivity extends AppCompatActivity {

    private Contact[] mContactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView recyclerView = findViewById(R.id.contactsRecyclerViewID);

        // Initialize the mContactList with some dummy data
        initializeData();

        // Specify an Adapter
        ListAdapter listAdapter = new ListAdapter(mContactList);
        recyclerView.setAdapter(listAdapter);

        // Size of the content do not change LayoutSize of RecyclerView
        recyclerView.setHasFixedSize(true);

        // Use a linear layout manager to show the list linearly
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initializeData() {
        // Sample fake data of the contactList
        mContactList = new Contact[]{
                new Contact("Chris","1234567890"),
                new Contact("Sam","2324435647"),
                new Contact("John","3545436347"),
                new Contact("Kelly","5657569086"),
                new Contact("Jake","4546753759"),
                new Contact("Helen","5467658984"),
                new Contact("Kate","7978908263"),
                new Contact("Jill","1234536086"),
                new Contact("Mike","9678548747"),
                new Contact("Ana","5446897465"),
                new Contact("George","5675798376"),
                new Contact("Vincent","6898756087"),
                new Contact("Mary","9775512685"),
                new Contact("Prince","9658865639"),
                new Contact("Jeff","6578898463"),
        };
    }
}

Step 5 : Create an Adapter Class called ListAdapter For the RecyclerView to display the Items as Follows :

public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> {

    private Contact[] mContactList;

    public ListAdapter(Contact[] contactList) {

        this.mContactList = contactList;
    }

    // Create new View to hold the data
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {

        // Create a new view with the list_item layout
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item,viewGroup,false);
        return new ViewHolder(view);
    }

    // Set the data in the view created
    // viewHolder holds the data
    // where you want to place the data is the position
    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHOlder, int position) {

        final Contact list = mContactList[position];

        // Set and display the data from Contact at this position
        viewHOlder.nameTxt.setText(mContactList[position].getName());
        viewHOlder.contactTxt.setText(mContactList[position].getmContactNum());

        // Set what happens when user clicks on the data viewHolder
        viewHOlder.dialLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(),"You clicked on : "+list.getName(),Toast.LENGTH_LONG).show();
            }
        });
    }

    // Returns the size of your Dataset
    @Override
    public int getItemCount() {

        return mContactList.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private TextView nameTxt;
        private TextView contactTxt;
        private LinearLayout dialLayout;

        private ViewHolder(@NonNull View itemView) {
            super(itemView);

            nameTxt = itemView.findViewById(R.id.nameTxtID);
            contactTxt = itemView.findViewById(R.id.contactTxtID);
            dialLayout = itemView.findViewById(R.id.contactLayoutID);
        }
    }
}

Step 6 : Finally the Contact class with the model for contact :

public class Contact {

    private String name;
    private String mContactNum;

    public Contact(String name, String contactNum) {
        this.name = name;
        this.mContactNum = contactNum;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getmContactNum() {
        return mContactNum;
    }

    public void setmContactNum(String contactNum) {
        this.mContactNum = contactNum;
    }
}

References

Android CardView API documentation

Get the sample code from github