RecyclerView using CardView with ItemClickListener in Android

In this blog, we’re going to see how to set onClickListener in recyclerView using cardView in android. If you’re not familiar with what RecyclerView and CardView is and how to implement CardView and RecyclerView in android then go through my previous blogs Implementation of RecyclerView and Implementation of CardView in android.

And we can check my previous blog where I explained how to implement a RecyclerView using CardView.

Steps of implementation of RecyclerView using CardView

This layout represents the items of the RecyclerView. To display the items in the RecyclerView, we used cardView for that. Below codes represent the item of the recyclerView where we used cardView widget:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardBackgroundColor="@android:color/white"
app:cardCornerRadius="8dp"
app:cardElevation="5dp"
app:contentPadding="10dp"
app:contentPaddingBottom="0dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
android:id="@+id/cardView">
<RelativeLayout
android:id="@+id/item"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="180dp"
android:scaleType="centerCrop"
android:id="@+id/image"
android:src="@drawable/ic_launcher_background"
android:contentDescription="CardImageViewDesc" />
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/image"
android:layout_marginStart="5dp"
android:fontFamily="sans-serif"
android:gravity="center_vertical"
android:text="LOREM IPSUM"
android:textSize="17sp"
android:textStyle="bold"
android:layout_marginTop="8dp"
android:textColor="@android:color/black"/>
<TextView
android:id="@+id/tag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="2dp"
android:fontFamily="sans-serif"
android:gravity="center_vertical"
android:text="Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups."
android:textStyle="italic"
android:textSize="15sp"
android:maxLines="2"
android:layout_toStartOf="@+id/imageButton"/>
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="?attr/selectableItemBackgroundBorderless"
android:src="@drawable/ic_action_name"
android:layout_below="@id/image"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:contentDescription="FavButtonDesc" />
</RelativeLayout></androidx.cardview.widget.CardView>
package com.codewithgolap.cardviewnrecyclerview;public class Model {
int image;
String name, tag;
public Model() {
}
public Model(int image, String name, String tag) {
this.image = image;
this.name = name;
this.tag = tag;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
package com.codewithgolap.cardviewnrecyclerview;import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
//create a list to pass our Model class
List<Model> modelList;
Context context;
public CustomAdapter(List<Model> modelList, Context context) {
this.modelList = modelList;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//inflate our custom view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_layout,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
//bind all custom views by its position
//to get the positions we call our Model class
final Model model = modelList.get(position);
holder.name.setText(model.getName());
holder.tag.setText(model.getTag());
holder.imageView.setImageDrawable(context.getResources().getDrawable(model.getImage()));
//click listener
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailsActivity.class);
intent.putExtra("image",model.getImage());
intent.putExtra("name",model.getName());
intent.putExtra("tag",model.getTag());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return modelList.size();
}
//all the custom view will be hold here or initialize here inside MyViewHolder
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView name, tag;
RelativeLayout relativeLayout;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
name = itemView.findViewById(R.id.name);
tag = itemView.findViewById(R.id.tag);
relativeLayout = itemView.findViewById(R.id.item);
}
}
}

Here we call our items which we need to display in the recyclerView, we set our adapter with recyclerView.

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recyclerView"/>
</RelativeLayout>

MainActivity.java:

package com.codewithgolap.cardviewnrecyclerview;import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity { RecyclerView recycler;
List<Model> modelList;
RecyclerView.Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<>();
recycler = findViewById(R.id.recyclerView);
recycler.setHasFixedSize(true);
recycler.setLayoutManager(new LinearLayoutManager(this));
//call our items
modelList.add(new Model(R.drawable.mount_everest,"Mount Everest","Mount Everest is Earth's highest mountain above sea level, located in the Mahalangur Himal sub-range of the Himalayas. The China–Nepal border runs across its summit point. The current official elevation of 8,848 m (29,029 ft), recognised by China and Nepal, was established by a 1955 Indian survey and confirmed by a 1975 Chinese survey."));
modelList.add(new Model(R.drawable.ktwo,"K2","K2, at 8,611 metres (28,251 ft) above sea level, is the second highest mountain in the world, after Mount Everest at 8,848 metres (29,029 ft). It is located on the China–Pakistan border between Baltistan in the Gilgit-Baltistan region of northern Pakistan, and Dafdar Township in Taxkorgan Tajik Autonomous County of Xinjiang, China."));
modelList.add(new Model(R.drawable.kanchenjunga,"Kangchenjunga","Kangchenjunga, also spelled Kanchenjunga, is the third highest mountain in the world. It rises with an elevation of 8,586 m (28,169 ft) in a section of the Himalayas called Kangchenjunga Himal delimited in the west by the Tamur River, in the north by the Lhonak Chu and Jongsang La, and in the east by the Teesta River."));
modelList.add(new Model(R.drawable.lhotse,"Lhotse","Lhotse is the fourth highest mountain in the world at 8,516 metres (27,940 ft), after Mount Everest, K2, and Kangchenjunga. Part of the Everest massif, Lhotse is connected to the latter peak via the South Col. Lhotse means “South Peak” in Tibetan."));
modelList.add(new Model(R.drawable.makalu,"Makalu ","Makalu is the fifth highest mountain in the world at 8,485 metres (27,838 ft). It is located in the Mahalangur Himalayas 19 km (12 mi) southeast of Mount Everest, on the border between Nepal and Tibet Autonomous Region, China. One of the eight-thousanders, Makalu is an isolated peak whose shape is a four-sided pyramid."));
modelList.add(new Model(R.drawable.chooyu,"Cho Oyu"," is the sixth-highest mountain in the world at 8,188 metres (26,864 ft) above sea level. Cho Oyu means \"Turquoise Goddess\" in Tibetan.The mountain is the westernmost major peak of the Khumbu sub-section of the Mahalangur Himalaya 20 km west of Mount Everest. The mountain stands on the China–Nepal border."));
modelList.add(new Model(R.drawable.dhaulagiri_mountain,"Dhaulagiri","The Dhaulagiri massif in Nepal extends 120 km (70 mi) from the Kaligandaki River west to the Bheri. This massif is bounded on the north and southwest by tributaries of the Bheri River and on the southeast by the Myagdi Khola. Dhaulagiri is the seventh highest mountain in the world at 8,167 metres (26,795 ft) above sea level, and the highest mountain within the borders of a single country (Nepal)."));
//init the adapter with model list and context
adapter = new CustomAdapter(modelList,getApplicationContext());
//set the adapter into recyclerView
recycler.setAdapter(adapter);
}
}

activity_details.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
tools:context=".DetailsActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerHorizontal="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:id="@+id/image"
android:src="@mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name"
android:text="Name"
android:textStyle="bold"
android:textSize="22sp"
android:layout_marginTop="8dp"
android:textColor="#000"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tag"
android:text="Tag"
android:layout_marginTop="8dp"
android:textColor="#A5A5A5"
android:textSize="18sp"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>

DetailsActivity.java

package com.codewithgolap.cardviewnrecyclerview;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class DetailsActivity extends AppCompatActivity { ImageView imageView;
TextView name, tag;
String alphaName, alphaTag;
int alphaImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
imageView = findViewById(R.id.image);
name = findViewById(R.id.name);
tag = findViewById(R.id.tag);
//get the intent
alphaName = getIntent().getStringExtra("name");
alphaTag = getIntent().getStringExtra("tag");
alphaImage = getIntent().getIntExtra("image",0);
//now set the get values in the respective widgets
name.setText(alphaName);
tag.setText(alphaTag);
imageView.setImageResource(alphaImage);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}

Output

For more content like this please visit GBAndroidBlogs

Happy Coding!!!

Hi everyone, myself Golap an Android app developer with UI/UX designer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store