javaandroidandroid-recyclerviewinterfacecardview

How to Use Recycler View With Card View & Interface in android java?


I want to use Cardview in recycle view and need its click event in any class with list position in android java


Solution

  • Step - 1 - Add Recyclerview in your MainActivity Layout

    <?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">
    
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/idRVCourse"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </RelativeLayout>
    

    Step - 2 - For our Card Here We Create New Resource File - layout -> new -> LayoutResourceFile -> New Layout Name / Here i give card_layout

    <?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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        app:cardBackgroundColor="@color/white"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp"
        app:cardMaxElevation="10dp"
        app:cardPreventCornerOverlap="true"
        app:cardUseCompatPadding="true">
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <ImageView
                android:id="@+id/idIVCourseImage"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginStart="10dp"
                android:layout_marginTop="10dp"
                android:layout_marginEnd="10dp"
                android:layout_marginBottom="10dp"
                android:contentDescription="@string/app_name"
                android:padding="5dp"
                android:src="@color/black" />
    
            <TextView
                android:id="@+id/idTVCourseName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:layout_marginTop="10dp"
                android:layout_toEndOf="@id/idIVCourseImage"
                android:text="course_name"
                android:textColor="@color/black"
                android:textSize="18sp"
                android:textStyle="bold" />
    
        </RelativeLayout>
    </androidx.cardview.widget.CardView>
    

    Step - 3 - Now We have to create one class for Model/Item, Here i make New class by name CourseModel

    public class CourseModel {
    
        private String course_name;
        private int course_image;
    
        // Constructor
        public CourseModel(String course_name, int course_image) {
            this.course_name = course_name;
            this.course_image = course_image;
        }
    
        public String getCourse_name() {
            return course_name;
        }
    
        public void setCourse_name(String course_name) {
            this.course_name = course_name;
        }
    
        public int getCourse_image() {
            return course_image;
        }
    
        public void setCourse_image(int course_image) {
            this.course_image = course_image;
        }
    }
    

    Step - 4 - Here we Have to make new Class as a Adapter here i give name CourseAdapter

    public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.Viewholder> {
    
        private Context context;
        private ArrayList<CourseModel> courseModelArrayList;
        // i3 create interface variable & add in constructor & solve main activity error by pass this in new CourseAdapter
        OnItemClickListener onItemClickListener;
        CourseModel item;
    
        public CourseAdapter(Context context, ArrayList<CourseModel> courseModelArrayList, OnItemClickListener onItemClickListener) {
            this.context = context;
            this.courseModelArrayList = courseModelArrayList;
            this.onItemClickListener = onItemClickListener;
        }
    
        @NonNull
        @Override
        public CourseAdapter.Viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
            return new Viewholder(view);
        }
    
        @Override
        public void onBindViewHolder(@NonNull CourseAdapter.Viewholder holder, int position) {
    
            CourseModel model = courseModelArrayList.get(position);
    
            holder.courseNameTV.setText(model.getCourse_name());
            holder.courseIV.setImageResource(model.getCourse_image());
            // can also set click event from Adapter class
            /*holder.courseIV.setOnClickListener(v -> {
                Toast.makeText(context, " -> "+model.getCourse_name(), Toast.LENGTH_SHORT).show();
            });*/
        }
    
        @Override
        public int getItemCount() {
            return courseModelArrayList.size();
        }
    
        public class Viewholder extends RecyclerView.ViewHolder {
            private ImageView courseIV;
            private TextView courseNameTV;
    
            public Viewholder(@NonNull View itemView) {
                super(itemView);
                courseIV = itemView.findViewById(R.id.idIVCourseImage);
                courseNameTV = itemView.findViewById(R.id.idTVCourseName);
    
                // i5
                itemView.setOnClickListener(view -> {
                    onItemClickListener.onItemClick(item,getAdapterPosition());
                    notifyDataSetChanged();
                });
            }
        }
    }
    

    Step - 5 - Now Lets Create Interface here i make interface by name OnItemClickListener

    // I1
    public interface OnItemClickListener {
        void onItemClick(CourseModel item, int position);
        void onLongItemClick(CourseModel item, int position);
    }
    

    Step - 6 - In This Last Step Apply Below code in Main Activity Here in ItemList You Can Put Your Images of Drawble

    // i2 implement interface & solve error
    public class MainActivity extends AppCompatActivity implements OnItemClickListener{
    
        private RecyclerView courseRV;
    
        private ArrayList<CourseModel> courseItemList;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            courseRV = findViewById(R.id.idRVCourse);
    
            itemList();
            
            // i4
            CourseAdapter courseAdapter = new CourseAdapter(this, courseItemList,this);
    
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    
            courseRV.setLayoutManager(linearLayoutManager);
            courseRV.setAdapter(courseAdapter);
        }
    
        private void itemList() {
            courseItemList = new ArrayList<>();
            courseItemList.add(new CourseModel("C",  R.drawable.ic_launcher_background));
            courseItemList.add(new CourseModel("C++",  R.drawable.ic_launcher_background));
            courseItemList.add(new CourseModel("Java",  R.drawable.ic_launcher_background));
            courseItemList.add(new CourseModel("Android",  R.drawable.ic_launcher_background));
            courseItemList.add(new CourseModel("Flutter", R.drawable.ic_launcher_background));
            courseItemList.add(new CourseModel("HTML",  R.drawable.ic_launcher_background));
            courseItemList.add(new CourseModel("CSS",  R.drawable.ic_launcher_background));
        }
    
        // i6
        @Override
        public void onItemClick(CourseModel item, int position) {
            Toast.makeText(this, ""+position+"\n"+courseItemList.get(position).getCourse_name(), Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onLongItemClick(CourseModel item, int position) {
    
        }
    }