CardView can represent the information in a card manner with a drop shadow called elevation and corner radius which looks consistent across the platform. It’s a kind of FrameLayout with a rounded corner background and shadow. We can easily design good looking UI when we combined CardView with RecyclerView. A CardView is a ViewGroup that can be added in our Activity or Fragment using a layout XML file.

 

Steps for using CardView

  1. Add the CardView dependency in build.gradle
    dependencies {
        ...
        implementation "androidx.cardview:cardview:1.0.0"
    }
  2. Create a layout for in res/layout/activity_main.xml and add following code.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".MainActivity">
          
      <!--  Recycler View  -->
      <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="none">
      </androidx.recyclerview.widget.RecyclerView>
        
    </RelativeLayout>

     

  3. Add CardView in the layout.
    Common attributes of a CardView that helps us to configure it in layout are

    • cardBackgroundColor : Set the background color for the CardView. We can also set the background color programmatically using setCardBackgroundColor(int color) method.
    • cardCornerRadius: Set the corner radius for the CardView. We can also set the corner radius programmatically using setRadius(float radius) method.
    • cardElevation : Set the elevation for the CardView. Elevation is used to show the shadow of the CardView. We can also set the card elevation value programmatically using setCardElevation(float elevation) method.

    Create a layout resource file, which renders the card view of a single row named it as rowlayout.xml to implement card view design.

    <androidx.cardview.widget.CardView
      android:id="@+id/card_view"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:cardElevation="20dp"
      android:layout_margin="10dp"
      app:contentPadding="20dp"
      xmlns:card_view="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      xmlns:android="http://schemas.android.com/apk/res/android">
    
      <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center">
    
        <ImageView
          android:id="@+id/image"
          android:layout_width="100dp"
          android:layout_height="100dp"
          android:layout_centerHorizontal="true"
          android:src="@drawable/person1" />
    
    
        <TextView
          android:id="@+id/name"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/image"
          android:layout_centerHorizontal="true"
          android:linksClickable="true"
          android:text="Hello"
          android:textColor="#000"
          android:textSize="20sp" />
      </RelativeLayout>
    
    </androidx.cardview.widget.CardView>
  4. Create custom adapter class.
    Custom Adapter class is required for RecyclerView. In custom Adapter two methods are important i.e. onCreateViewHolder() (inflate the layout item xml and pass it to View Holder) and onBindViewHolder() (set the data in the view’s with the help of ViewHolder). Finally we implement the setOnClickListener() event on itemview and on click of item we display the selected image in full size in the next Activity.

    public class CustomAdapter extends RecyclerView.Adapter {
    
      ArrayList personNames;
      ArrayList personImages;
      Context context;
    
      public CustomAdapter(Context context, ArrayList personNames, ArrayList personImages) {
        this.context = context;
        this.personNames = personNames;
        this.personImages = personImages;
      }
    
      @Override
      public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    
        // Infalte the item Layout
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
    
        // Set the view's size, margins, paddings and layout parameters
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
      }
    
      @Override
      public void onBindViewHolder(MyViewHolder holder, final int position) {
    
        // Set the data in items
        holder.name.setText(personNames.get(position));
        holder.image.setImageResource(personImages.get(position));
    
        // Implement setOnClickListener event on item view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
    
          @Override
          public void onClick(View view) {
            // Open another activity on item click
            Intent intent = new Intent(context, SecondActivity.class);
            intent.putExtra("image", personImages.get(position));
            context.startActivity(intent);
          }
        });
      }
    
      @Override
      public int getItemCount() {
        return personNames.size();
      }
    
      public class MyViewHolder extends RecyclerView.ViewHolder {
    
        TextView name;
        ImageView image;
    
        public MyViewHolder(View itemView) {
    
          super(itemView);
    
          name = (TextView) itemView.findViewById(R.id.name);
          image = (ImageView) itemView.findViewById(R.id.image);
        }
      }
    }
  5.  Create launcher activity
    Now create an instance of CustomAdapter and setAdapter( ) to RecyclerView.

    public class MainActivity extends AppCompatActivity {
    
      // ArrayList for person names
      ArrayList personNames = new ArrayList<>(Arrays.asList("Person 1", "Person 2", "Person 3", "Person 4"));
      ArrayList personImages = new ArrayList<>(Arrays.asList(R.drawable.person1, R.drawable.person2, R.drawable.person3, R.drawable.person4));
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // get reference of RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    
        // set a LinearLayoutManager with default orientaion
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);
    
        // Send the reference and data to Adapter
        CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, personNames,personImages);
        recyclerView.setAdapter(customAdapter);
      }
    }
  6. Handle on setOnClickListener()
    Get Intent which was set from adapter of Previous Activity and then set the image in ImageView.

    public class SecondActivity extends AppCompatActivity {
    
      ImageView selectedImage;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        selectedImage = findViewById(R.id.selectedImage);
    
        // Get Intent from calling Activity
        Intent intent = getIntent(); 
        selectedImage.setImageResource(intent.getIntExtra("image", 0));
      }
    }