0
package com.example.cardviewapp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

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

    public Context context;
    public ArrayList<HarryPotterNovel> harryPotterNovel;

    public CustomAdapter(Context context, ArrayList<HarryPotterNovel> harryPotterNovel) {
        this.context = context;
        this.harryPotterNovel = harryPotterNovel;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView imageView;
        TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            this.imageView = itemView.findViewById(R.id.imageView);
            this.textView = itemView.findViewById(R.id.textView);
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.card_view_items, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        HarryPotterNovel harryPotterNovel2 = harryPotterNovel.get(position);
        holder.textView.setText(harryPotterNovel2.getTitle());
        holder.imageView.setImageResource(harryPotterNovel2.getImage());
    }

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

What is the use for the context object in this code? I'm still a beginner, please help out. If possible, can you explain the workings of the overridden methods. I don't know why all the courses I've come across do not seem to explain in detail the functionality of the methods, they just tell you to typem but they never explain why you do somethings. Can somebody explain all the methods in detail because I'm really stuck? Like why do we return ViewHolder object? Or like the LayoutInflater parameters and like how are the methods called?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Have you tried reading the [RecyclerView documentation](https://developer.android.com/guide/topics/ui/layout/recyclerview)? It explains in detail what each overridden method does in addition to showing annotated code samples. – Tyler V May 28 '22 at 02:42
  • It's used in layout inflation within `onCreateViewHolder()`; but you can totally omit it and use `parent.getContext()` instead – Zain May 28 '22 at 04:53

0 Answers0