Cardview Android Example [beginners]

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

Since, Cardview Android is part of material design.It's such a view which 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,

In the above picture, every boxes 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 explanation about the android cardview. Let get into the coding part.

Cardview android example with Recyclerview

In this post, I am going to create 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 am already have a post on recyclerview in android. 

implementation "androidx.cardview:cardview:1.0.0" 
implementation 'androidx.recyclerview:recyclerview:1.1.0'

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. 

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

Create model class for the Movies.  So, my movie.java.

public class Movie {

    private String title;
    private int image;

    public Movie(String title, int image) {
        this.title = title;
        this.image = image;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }
}

In your MainActivity.java,  create movieList items.

private void prepareMovie(){
        Movie movie = new Movie("Star Wars The Last Jedi",R.drawable.star_war);
        movieList.add(movie);
        movie = new Movie("Coco",R.drawable.coco);
        movieList.add(movie);
        movie = new Movie("Justice League ",R.drawable.justice_league);
        movieList.add(movie);
        movie = new Movie("Thor: Ragnarok",R.drawable.thor_ragnarok);
        movieList.add(movie);
}

3. Create recyclerview adapter with cardview layout

adapter needs to be created to list all the movies in the recyclerview. So, we are going to create 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="match_parent"
            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"
            cardView:layout_constraintBottom_toBottomOf="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.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

in the cardview layout,

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

Also, using cardView:cardElevation for the shadow outside the cardview. 

the cardview UI looks like,

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

RecyclerViewAdapter.java

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>{

    private List<Movie> movieList;

    RecyclerViewAdapter(List<Movie> movieList){
        this.movieList = movieList;
    }

    @Override
    public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_adapter_layout,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerViewAdapter.MyViewHolder holder, final int position) {

        final Movie movie = movieList.get(position);

        holder.title.setText(movie.getTitle());
        holder.image.setBackgroundResource(movie.getImage());
    }

    @Override
    public int getItemCount() {
        return movieList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView title;
        private ImageView image;
        private CardView cardView;

        public MyViewHolder(View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            image = itemView.findViewById(R.id.image);
            cardView = itemView.findViewById(R.id.carView);
        }
    }
}

Step 4  - setup recyclerview with adapter 

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

movieList = new ArrayList<>();
        prepareMovie();
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerViewAdapter = new RecyclerViewAdapter(movieList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);


        recyclerViewAdapter.setOnItemClickListener(new ClickListener<Movie>(){
            @Override
            public void onItemClick(Movie data) {
                Toast.makeText(MainActivity.this, data.getTitle(), Toast.LENGTH_SHORT).show();
            }
        });

        recyclerView.setAdapter(recyclerViewAdapter);

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

Bonus 

setup click listener for cardview in android

to set click listener in cardview,

  1. create click listener interface.
    interface ClickListener<T> {
        void onItemClick(T data);
    }
  2. in recyclerview adapter, create clickListener instance and also create setOnItemClickListener method to attach the click listener to mainActivity.
    public void setOnItemClickListener(ClickListener<Movie> movieClickListener) {
            this.clickListener = movieClickListener;
    }
  3. implement click listener for cardview and call the onItemClick method.
    holder.cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickListener.onItemClick(movie);
                }
    });
  4. Finally, In your mainActivity pass the clickListener implementation to the recyclerview adapter.
    recyclerViewAdapter.setOnItemClickListener(new ClickListener<Movie>(){
                @Override
                public void onItemClick(Movie data) {
                    Toast.makeText(MainActivity.this, data.getTitle(), Toast.LENGTH_SHORT).show();
                }
    });

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 in github.

Conclusion

Thanks for reading. Now a days, Cardview is important component in android. So, try this example and let me know your feedback in comments.

Leave a Reply

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