Android RecyclerView Example – Multiple ViewTypes
Introduction
In Android development, the RecyclerView is a powerful and flexible widget for displaying a scrolling list of elements. When dealing with complex lists that contain different types of items, it’s common to use multiple view types within a RecyclerView. This can be achieved by implementing the getItemViewType method in your adapter and creating different view holders for each view type.
We will incorporate three types of views (text, image, audio), each utilizing three distinct layouts. The adapter class defines the specific implementation for each view type.
Here’s a step-by-step example of how to create a RecyclerView with multiple view types:
Create Model Classes:
Define the model classes for different types of items. For example, let’s consider a list with two types of items – TextItem and ImageItem.
Example:
public class TextItem {
   private String text;
    public TextItem(String text) {
       this.text = text;
   }
    public String getText() {
       return text;
   }
}
public class ImageItem {
    private int imageResId;
    public ImageItem(int imageResId) {
        this.imageResId = imageResId;
    }
    public int getImageResId() {
        return imageResId;
    }
}
In this example:
TextItem is a simple class representing an item with a text content.
ImageItem is a class representing an item with an image resource ID.
These classes encapsulate the data for each type of item you want to display in your RecyclerView. You can customize them based on the specific data you need for your application.
Create View Holders:
Create view holders for each item type by extending the RecyclerView.ViewHolder class.
// TextItemViewHolder.javaÂ
public class TextItemViewHolder extends RecyclerView.ViewHolder {
    private TextView textView;
    public TextItemViewHolder(View itemView) {
        super(itemView);
        textView = itemView.findViewById(R.id.text_view);
    }
    public void bind(TextItem textItem) {
        textView.setText(textItem.getText());
    }
}
// ImageItemViewHolder.java
import android.view.View;
import android.widget.ImageView;
import androidx.recyclerview.widget.RecyclerView;
public class ImageItemViewHolder extends RecyclerView.ViewHolder {
    private ImageView imageView;
    public ImageItemViewHolder(View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.image_view); // Assuming there is an ImageView with this ID in your item layout
    }
    public void bind(ImageItem imageItem) {
        imageView.setImageResource(imageItem.getImageResId());
    }
}
In these examples:
- TextItemViewHolder holds a reference to a TextView within the item layout and provides a bind method to update its content based on a TextItem instance.
- ImageItemViewHolder holds a reference to an ImageView within the item layout and provides a bind method to update its image resource based on an ImageItem instance.
Create RecyclerView Adapter:
Create an adapter class by extending RecyclerView.Adapter. Override the getItemViewType method to return the view type based on the position in the list.
public class MultiViewTypeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
   private List<Object> items;
    private static final int VIEW_TYPE_TEXT = 1;
   private static final int VIEW_TYPE_IMAGE = 2;
    public MultiViewTypeAdapter(List<Object> items) {
       this.items = items;
   }
    @Override
   public int getItemViewType(int position) {
       if (items.get(position) instanceof TextItem) {
           return VIEW_TYPE_TEXT;
       } else if (items.get(position) instanceof ImageItem) {
           return VIEW_TYPE_IMAGE;
       }
       return -1; // Handle unknown view type
   }
    @NonNull
   @Override
   public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
       LayoutInflater inflater = LayoutInflater.from(parent.getContext());
       View view;
        switch (viewType) {
           case VIEW_TYPE_TEXT:
               view = inflater.inflate(R.layout.item_text, parent, false);
               return new TextItemViewHolder(view);
           case VIEW_TYPE_IMAGE:
               view = inflater.inflate(R.layout.item_image, parent, false);
               return new ImageItemViewHolder(view);
           default:
               // Handle unknown view type
               return null;
       }
   }
    @Override
   public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
       Object item = items.get(position);
        switch (holder.getItemViewType()) {
           case VIEW_TYPE_TEXT:
               ((TextItemViewHolder) holder).bind((TextItem) item);
               break;
           case VIEW_TYPE_IMAGE:
               ((ImageItemViewHolder) holder).bind((ImageItem) item);
               break;
           default:
               // Handle unknown view type
               break;
       }
   }
    @Override
   public int getItemCount() {
       return items.size();
   }
}
In this adapter:
- getItemViewType: Determines the view type based on the item at the given position.
- onCreateViewHolder: Inflates the appropriate layout for each view type and returns the corresponding ViewHolder.
- onBindViewHolder: Binds the data to the appropriate ViewHolder based on the view type.
- getItemCount: Returns the total number of items in the dataset.
Create Layouts:
Create layout files for the TextItem and ImageItem views (item_text.xml and item_image.xml).
Example:
<!-- item_text.xml -->
<TextView
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"/>
<!-- item_image.xml -->
<ImageView
   android:id="@+id/image_view"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:scaleType="centerCrop"/>
   android:id="@+id/text_view"
   xmlns:android="http://schemas.android.com/apk/res/android"
These layouts define the appearance of the individual items in your RecyclerView. Customize the layouts based on your design preferences and the data you want to display in each item.
Usage in Activity or Fragment:
In your activity or fragment, set up the RecyclerView and attach the adapter:
List<Object> items = new ArrayList<>();
items.add(new TextItem(“Hello, this is a text item.”));
items.add(new ImageItem(R.drawable.sample_image));
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new MultiViewTypeAdapter(items));
OUTPUT:
Make sure to replace R.layout.item_text and R.layout.item_image with the actual layout resource IDs for your text and image items.
Conclusion:
This example demonstrates the basic structure of a RecyclerView with multiple view types. Adjust it according to your specific needs and customize the layout files, view holders, and model classes accordingly.