Android

How to use Multiple RecyclerView in Android

Pinterest LinkedIn Tumblr

This is the 6th tutorial in a RecyclerView Series which covers the fundamentals of RecyclerView. If you already have a solid understanding of how to create a RecyclerView, carry on. Otherwise, consider starting with this.

Jump to section

Demo

Multiple RecyclerView Example

Step-1 (Create a new project)

Create a new project and select the blank template.

Step-2 (Add dependencies)

Go to the build.gradle.xml file and add the below code in the dependencies section and sync

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

Step-3 (Project Resources)

1- Go to the colors.xml file and add the below code

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <!-- App colors -->
    <color name="color_user_card_bg">#0F2046</color>
    <color name="color_blog_card_bg">#1D2840</color>
    <color name="color_tv_posted_date">#FA6A00</color>
    <color name="color_bg">#021236</color>

</resources>

2- Open the strings.xml file and add the below code to it

<resources>
    <string name="app_name">MultipleRecyclerViewExample</string>
    <string name="demo_title">Multiple RecyclerView Listing Example</string>
    <string name="str_community_blog">Community Blogs</string>


    <string name="user_john">John</string>
    <string name="user_jordan">Jordan</string>
    <string name="user_sam">Sam</string>
    <string name="user_alex">Alex</string>
    <string name="user_harry">Harry</string>
    <string name="str_age_format">%d year old</string>
    <string name="str_date_format">%d mint ago</string>
    <string name="str_random_title">Random Title</string>
    <string name="str_random_description">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Molestie at elementum eu facilisis sed. Ornare arcu dui vivamus arcu felis bibendum ut</string>

    <!-- Array of user -->
    <string-array name="arr_users">
        <item>@string/user_john</item>
        <item>@string/user_jordan</item>
        <item>@string/user_sam</item>
        <item>@string/user_alex</item>
        <item>@string/user_harry</item>
    </string-array>
</resources>

Step-4 (Design a layout for RecyclerView rows)

1- Create a layout file that defines what the horizontal row looks like. Navigate to the app > res > layout > Right-click on it> New > Layout Resource File called adapter_user_profile.xml. Add the below code

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="230dp"
    app:cardBackgroundColor="@color/color_user_card_bg"
    app:cardUseCompatPadding="true"
    app:cardCornerRadius="5dp"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imgUser"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="15dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/user" />
        <TextView
            android:id="@+id/tvUserName"
            android:text="@string/user_john"
            android:textSize="22sp"
            android:textStyle="bold"
            android:textColor="@color/white"
            android:layout_marginTop="5dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imgUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:id="@+id/tvUserAge"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:layout_width="wrap_content"
            android:textColor="@color/white"
            android:layout_margin="5dp"
            android:text="@string/str_age_format"
            android:layout_height="wrap_content"/>
    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

2- Create a layout file that defines what the vertical row looks like. Navigate to the app > res > layout > Right-click on it> New > Layout Resource File called adapter_blog.xml. Add the below code

<?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="200dp"
    app:cardBackgroundColor="@color/color_blog_card_bg"
    app:cardUseCompatPadding="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="@string/str_random_title"
            android:textColor="@color/white"
            android:textSize="20sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tvDescription"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:text="@string/str_random_description"
            android:textColor="@color/white"
            android:textSize="18sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvTitle" />


        <TextView
            android:id="@+id/tvPostedDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="@string/str_date_format"
            android:textColor="@color/color_tv_posted_date"
            android:textSize="16sp"
            app:layout_constraintTop_toBottomOf="@+id/tvDescription"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

Step-5 (Working with Modal class)

1- Create a java class and renamed it with UserProfileM.java. UserProfileM.java class will have name and age properties. UserProfileM.java class will use for Horizontal RecyclerView Adapter. Add the below code to it.

package com.example.multiplerecyclerviewexample;

public class UserProfileM {
    private String name;
    private int age;

    public UserProfileM(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

2- Create a new Java class and renamed it with BlogM.java. BlogM.java class will have three properties, title, description, and time. BlogM.java class will use for Vertical RecyclerView Adapter. Add the below code to it.

package com.example.multiplerecyclerviewexample;

public class BlogM {
    private String title;
    private String description;
    private int minAgo = 0;

    public BlogM(String title, String description, int minAgo) {
        this.title = title;
        this.description = description;
        this.minAgo = minAgo;
    }

    public int getMinAgo() {
        return minAgo;
    }

    public void setMinAgo(int minAgo) {
        this.minAgo = minAgo;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Step-6 (Create RecyclerView Adapters)

1- Create a Java class and renamed it with AdapterUserProfile.java. AdapterUserProfile.java class will extend the RecyclerView adapter class and will use for horizontal listing. Add the below code to it

package com.example.multiplerecyclerviewexample;

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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class AdapterUserProfile extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<UserProfileM> userProfileMS;
    private Context _context;


    AdapterUserProfile(List<UserProfileM> UserProfileM) {
        this.userProfileMS = UserProfileM;
    }

    private class UserProfileViewHolder extends RecyclerView.ViewHolder {
        private TextView tvUserName;
        private TextView tvUserAge;

        public UserProfileViewHolder(View itemView) {
            super(itemView);
            tvUserName = itemView.findViewById(R.id.tvUserName);
            tvUserAge = itemView.findViewById(R.id.tvUserAge);
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        _context = parent.getContext();
        View v1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_user_profile, parent, false);
        return new UserProfileViewHolder(v1);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        UserProfileViewHolder listItemViewHolder = (UserProfileViewHolder) holder;
        UserProfileM userProfileM = userProfileMS.get(position);
        listItemViewHolder.tvUserName.setText(userProfileM.getName());
        listItemViewHolder.tvUserAge.setText(String.format(_context.getString(R.string.str_age_format), userProfileM.getAge()));
    }

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

2- Create a new Java class and renamed it AdapterBlog.java. As UserProfileAdapter.java, AdpaterBlog.java class will extend the RecyclerView adapter class and will use for horizontal listing.

package com.example.multiplerecyclerviewexample;

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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class AdapterBlog extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<BlogM> blogMList;
    private Context _context;


    AdapterBlog(List<BlogM> blogMList) {
        this.blogMList = blogMList;
    }

    private class BlogViewHolder extends RecyclerView.ViewHolder {
        private TextView tvTitle;
        private TextView tvDescription;
        private TextView tvPostedDate;

        public BlogViewHolder(View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tvTitle);
            tvDescription = itemView.findViewById(R.id.tvDescription);
            tvPostedDate = itemView.findViewById(R.id.tvPostedDate);
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        _context = parent.getContext();
        View v1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_blog, parent, false);
        return new BlogViewHolder(v1);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        BlogViewHolder blogViewHolder = (BlogViewHolder) holder;
        BlogM blogM = blogMList.get(position);
        blogViewHolder.tvTitle.setText(blogM.getTitle());
        blogViewHolder.tvDescription.setText(blogM.getDescription());
        blogViewHolder.tvPostedDate.setText(String.format(_context.getString(R.string.str_date_format),blogM.getMinAgo()));
    }

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

Step-7 (activity_main.xml file)

In the activity_main.xml file, two RecyclerView will use for different orientations. RecyclerView on the top position will use for horizontal listing and RecyclerView on the bottom position will use for vertical listing. Two LinearLayoutManager objects will use for horizontal and vertical orientations.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="@color/color_bg"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvDemoTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text="@string/demo_title"
        android:textColor="@color/white"
        android:textSize="22sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rcvUserListing"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvDemoTitle" />

    <TextView
        android:id="@+id/tvCommunity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text="@string/str_community_blog"
        android:textColor="@color/white"
        android:textSize="22sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/rcvUserListing" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rcvBlogListing"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvCommunity" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step-8 (MainActivity.java)

Go to the MainActivity.java file and add the below code. Comments are added inside the code for understanding the code. If you get confuse post a comment below.

package com.example.multiplerecyclerviewexample;

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;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private RecyclerView rcvUserListing;
    private RecyclerView rcvBlogListing;
    private AdapterUserProfile adapterUserProfile;
    private AdapterBlog adapterBlog;
    private List<UserProfileM> userProfileMS;
    private List<BlogM> blogMList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initComponents();
        prepareUserDummyData();
        prepareBlogDummyData();
    }

    /**
     * initialize the components
     */
    private void initComponents() {
        // user listing
        rcvUserListing = findViewById(R.id.rcvUserListing); // RecyclerView for horizontal listing display
        userProfileMS = new ArrayList<>();
        LinearLayoutManager userLayoutManager = new LinearLayoutManager(this);
        userLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); // for horizontal listing
        rcvUserListing.setLayoutManager(userLayoutManager);
        adapterUserProfile = new AdapterUserProfile(userProfileMS); // set the user profile data to the user profile adapter
        rcvUserListing.setAdapter(adapterUserProfile); // set the user adapter to horizontal RecyclerView

        // blog listing
        rcvBlogListing = findViewById(R.id.rcvBlogListing); // RecyclerView for vertical listing display
        blogMList = new ArrayList<>();
        LinearLayoutManager blogLayoutManager = new LinearLayoutManager(this);
        blogLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); // for vertical listing
        rcvBlogListing.setLayoutManager(blogLayoutManager);
        adapterBlog = new AdapterBlog(blogMList); // set the listing data to the blog adapter
        rcvBlogListing.setAdapter(adapterBlog); // now set blog adapter to vertical RecyclerView
    }

    /**
     * Setup the dummy data for user profile
     */
    private void prepareUserDummyData() {
        String[] userNamesArr = getResources().getStringArray(R.array.arr_users);
        for(String str:userNamesArr){
            userProfileMS.add(new UserProfileM(str,getRandomNumber(15,60)));
        }
        adapterUserProfile.notifyDataSetChanged();
    }

    /**
     * Setup the dummy data for listing display
     */
    private void prepareBlogDummyData(){
        for(int i = 0; i<10; i++){
            blogMList.add(new BlogM(getString(R.string.str_random_title),getString(R.string.str_random_description),getRandomNumber(1,20)));
        }
        adapterBlog.notifyDataSetChanged();
    }


    /**
     * 
     * @param min min value
     * @param max max value
     * @return will return the random value between min and max value
     */
    private int getRandomNumber(int min, int max) {
        return (int) ((Math.random() * (max - min)) + min);
    }
}

Step-9 (Download project resources)

// will add download resources code

Thanks for reading the tutorial. Subscribe to my YouTube channel. Like and Share my Facebook page with your friends.

Write A Comment