Open In App

How to Implement RecyclerView in a Fragment in Android?

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application.  A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It has its own lifecycle and can receive input events and interact with the user. Fragments were introduced in Android 3.0 (API level 11) as a way to create more flexible and dynamic user interfaces for larger-screen devices, such as tablets. They allow developers to reuse UI components across different screen sizes and orientations, and to create more efficient and responsive applications.

Fragments can be added, removed, replaced, or rearranged dynamically at runtime, which makes it easier to create complex and flexible layouts. They are often used in combination with the FragmentManager class, which manages the lifecycle of fragments and their interaction with the hosting activity. In this article we are going to see how can we implement a RecycleView within a Fragment in Android, In this project, by clicking a button we are moving to a fragment and a RecycleView is displayed within the Fragment. To implement RecycleView in Fragment we have to follow some steps :

  1. Create a RecyclerView layout
  2. Create a RecyclerView Adapter
  3. Set the RecyclerView Adapter and LayoutManager  in our fragment onCreateView method
  4. Bind data to the RecyclerView Adapter

To learn more about RecycleView in Android you can visit this article RecyclerView in Android with Example.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Change the StatusBar Color

Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.

<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>

Step 3: Creating a new Fragment 

In this step, we have to create a new Fragment named as FirstFragment.

 

Click on Fragment(Blank) and create a new Fragment.

Step 4: Creating a layout for RecyclerView

Navigate to app > res > layout then Create a new layout resource file and name it items_list.xml. It includes two Text Views for displaying the Name and Emails of the Employees. Comments are added inside the code for a better understanding of the Code.

XML




<?xml version="1.0" encoding="utf-8"?>
<!--LinearLayout orientation horizontal -->
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/llMain"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="10dp">
 
    <!--TextView for displaying Name -->
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:background="@color/white"
        android:foreground="?attr/selectableItemBackground"
        app:cardCornerRadius="3dp"
        app:cardElevation="3dp"
        app:cardUseCompatPadding="true">
 
        <!--LinearLayout orientation Vertical -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="15dp"
            android:orientation="vertical">
           
            <!--TextView for displaying Name -->
            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@android:color/black"
                android:textSize="20sp"
                tools:text="Name" />
 
            <!--TextView for displaying Email -->
            <TextView
                android:id="@+id/tvEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="#454545"
                android:textSize="16sp"
                tools:text="Email" />
 
        </LinearLayout>
 
    </androidx.cardview.widget.CardView>
 
</LinearLayout>


Step 5: Working fragment_first.xml

Navigate to app > res > layout > fragment_first.xml. In this fragment layout file, we are going to implement the recyclerView.

XML




<?xml version="1.0" encoding="utf-8"?>
<!--Linear layout orientation vertical-->
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".FirstFragment">
     
      <!--Linear layout orientation vertical-->
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
         
          <!--TextView-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:textSize="20sp"
            android:textColor="@color/black"
            android:textStyle="bold"
            android:text="Fragment 1"/>
         
          <!--RecyclerView-->
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycleView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:listitem="@layout/items_list"/>
       
    </LinearLayout>
   
</LinearLayout>


Step 6: Working with activity_main.xml

Navigate to the app > res > layout > activity_main.xml and add the below code to the activity_main.xml file. In this layout, we have created a button by clicking this button the fragment layout will be displayed.

XML




<?xml version="1.0" encoding="utf-8"?>
<!--Linear Layout-->
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/llMain"
    tools:context=".MainActivity">
   
        <!--Frame layout-->
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/frame_layout">
           
                <!--Button-->
                <Button
                    android:id="@+id/btn_frag"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:foreground="?attr/selectableItemBackground"
                    android:background="@color/Green"
                    android:text="RecycleView In Fragment"/>
           
        </FrameLayout>
</LinearLayout>


Step 7: Creating an Employee Model

In this step, we are going to create an employee model for our RecyclerView. It Contains the Employee’s Name and Employee email Id.  Below is the code for the Employee model. Navigate to app >java > your package name >  Create a Kotlin data class named it Employee.kt.

Kotlin




package com.example.gfg
data class Employee(
    val name:String,   // name of the employee
    val email:String   // email of the employee
):java.io.Serializable


Java




package com.example.gfg;
 
import java.io.Serializable;
 
public class Employee implements Serializable {
    private final String name;   // name of the employee
    private final String email;  // email of the employee
 
    public Employee(String name, String email) {
        this.name = name;
        this.email = email;
    }
 
    public String getName() {
        return name;
    }
 
    public String getEmail() {
        return email;
    }
}


Step 8: Creating Employee ArrayList

In this step, we are going to prepare the ArrayList of employees with the employee name and employee email. Below is the code for Creating and adding data to the ArrayList. Comments are added inside the code for a better understanding of the Code. Navigate to app > java >your package name > Create a Kotlin Object named Constants.

Kotlin




package com.example.gfg
 
object Constants {
    // Arraylist and return the Arraylist
    fun getEmployeeData():ArrayList<Employee>{
        // create an arraylist of type employee class
        val employeeList=ArrayList<Employee>()
        val emp1=Employee("Chinmaya Mohapatra","chinmaya@gmail.com")
        employeeList.add(emp1)
        val emp2=Employee("Ram prakash","ramp@gmail.com")
        employeeList.add(emp2)
        val emp3=Employee("OMM Meheta","mehetaom@gmail.com")
        employeeList.add(emp3)
        val emp4=Employee("Hari Mohapatra","harim@gmail.com")
        employeeList.add(emp4)
        val emp5=Employee("Abhisek Mishra","mishraabhi@gmail.com")
        employeeList.add(emp5)
        val emp6=Employee("Sindhu Malhotra","sindhu@gmail.com")
        employeeList.add(emp6)
        val emp7=Employee("Anil sidhu","sidhuanil@gmail.com")
        employeeList.add(emp7)
        val emp8=Employee("Sachin sinha","sinhas@gmail.com")
        employeeList.add(emp8)
        val emp9=Employee("Amit sahoo","sahooamit@gmail.com")
        employeeList.add(emp9)
        val emp10=Employee("Raj kumar","kumarraj@gmail.com")
        employeeList.add(emp10)
 
        return  employeeList
    }
}


Java




package com.example.gfg;
 
import java.util.ArrayList;
 
public class Constants {
    // ArrayList and return the ArrayList
    public static ArrayList<Employee> getEmployeeData()
    {
        // create an ArrayList of type Employee class
        ArrayList<Employee> employeeList
            = new ArrayList<Employee>();
        Employee emp1 = new Employee("Chinmaya Mohapatra",
                                     "chinmaya@gmail.com");
        employeeList.add(emp1);
        Employee emp2
            = new Employee("Ram prakash", "ramp@gmail.com");
        employeeList.add(emp2);
        Employee emp3 = new Employee("OMM Meheta",
                                     "mehetaom@gmail.com");
        employeeList.add(emp3);
        Employee emp4 = new Employee("Hari Mohapatra",
                                     "harim@gmail.com");
        employeeList.add(emp4);
        Employee emp5 = new Employee(
            "Abhisek Mishra", "mishraabhi@gmail.com");
        employeeList.add(emp5);
        Employee emp6 = new Employee("Sindhu Malhotra",
                                     "sindhu@gmail.com");
        employeeList.add(emp6);
        Employee emp7 = new Employee("Anil sidhu",
                                     "sidhuanil@gmail.com");
        employeeList.add(emp7);
        Employee emp8 = new Employee("Sachin sinha",
                                     "sinhas@gmail.com");
        employeeList.add(emp8);
        Employee emp9 = new Employee("Amit sahoo",
                                     "sahooamit@gmail.com");
        employeeList.add(emp9);
        Employee emp10 = new Employee("Raj kumar",
                                      "kumarraj@gmail.com");
        employeeList.add(emp10);
 
        return employeeList;
    }
}


Step 9: Create an Adapter for our RecyclerView

In this step, we are going to create an adapter class for our recycleView and override its three-member functions. Navigate to app > java >your package name > Create a Kotlin Object named Adapter. Below is the code for the ItemAdapter class. Comments are added inside the code for a better understanding of the Code.

Kotlin




package com.example.gfg
 
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
 
class Adapter(private val emplist: ArrayList<Employee>) : RecyclerView.Adapter<Adapter.MyViewHolder>() {
 
    // This method creates a new ViewHolder object for each item in the RecyclerView
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        // Inflate the layout for each item and return a new ViewHolder object
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.items_list, parent, false)
        return MyViewHolder(itemView)
    }
 
    // This method returns the total
    // number of items in the data set
    override fun getItemCount(): Int {
        return emplist.size
    }
 
    // This method binds the data to the ViewHolder object
    // for each item in the RecyclerView
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val currentEmp = emplist[position]
        holder.name.text = currentEmp.name
        holder.email.text = currentEmp.email
    }
 
    // This class defines the ViewHolder object for each item in the RecyclerView
    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val name: TextView = itemView.findViewById(R.id.tvName)
        val email: TextView = itemView.findViewById(R.id.tvEmail)
    }
}


Java




package com.example.gfg;
 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
import androidx.recyclerview.widget.RecyclerView;
 
import java.util.ArrayList;
 
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
    private ArrayList<Employee> emplist;
 
    public Adapter(ArrayList<Employee> emplist) {
        this.emplist = emplist;
    }
 
    // This method creates a new ViewHolder object for each item in the RecyclerView
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Inflate the layout for each item and return a new ViewHolder object
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_list, parent, false);
        return new MyViewHolder(itemView);
    }
 
    // This method returns the total
    // number of items in the data set
    @Override
    public int getItemCount() {
        return emplist.size();
    }
 
    // This method binds the data to the ViewHolder object
    // for each item in the RecyclerView
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Employee currentEmp = emplist.get(position);
        holder.name.setText(currentEmp.getName());
        holder.email.setText(currentEmp.getEmail());
    }
 
    // This class defines the ViewHolder object for each item in the RecyclerView
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView name;
        private TextView email;
 
        public MyViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.tvName);
            email = itemView.findViewById(R.id.tvEmail);
        }
    }
}


Step 10: Working with FirstFragment.kt

Navigate to the app > java >your package name > FirstFragment, in this file, we are going to initialize the RecyclerView and its adapter within the onCreateView method. Add the below code to your FirstFragment.kt file.

Kotlin




override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      super.onViewCreated(view, savedInstanceState)
      // getting the employeelist
      val employelist=Constants.getEmployeeData()
      // Assign employeelist to ItemAdapter
      val itemAdapter=Adapter(employelist)
      // Set the LayoutManager that
      // this RecyclerView will use.
      val recyclerView:RecyclerView=view.findViewById(R.id.recycleView)
      recyclerView.layoutManager = LinearLayoutManager(context)
      // adapter instance is set to the
      // recyclerview to inflate the items.
      recyclerView.adapter = itemAdapter
  }


Java




@Override
public void
onViewCreated(@NonNull View view,
              @Nullable Bundle savedInstanceState)
{
    super.onViewCreated(view, savedInstanceState);
    // getting the employeelist
    ArrayList<Employee> employelist
        = Constants.getEmployeeData();
    // Assign employeelist to ItemAdapter
    Adapter itemAdapter = new Adapter(employelist);
    // Set the LayoutManager that
    // this RecyclerView will use.
    RecyclerView recyclerView
        = view.findViewById(R.id.recycleView);
    recyclerView.setLayoutManager(
        new LinearLayoutManager(getContext()));
    // adapter instance is set to the
    // recyclerview to inflate the items.
    recyclerView.setAdapter(itemAdapter);
}


Full Code of the FirstFragment.kt:

Kotlin




package com.example.gfg
 
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
 
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
 
/**
 * A simple [Fragment] subclass.
 * Use the [FirstFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class FirstFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }
 
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false)
    }
 
    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment FirstFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            FirstFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
 
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
         
        // getting the employeelist
        val employelist=Constants.getEmployeeData()
 
        // Assign employeelist to ItemAdapter
        val itemAdapter=Adapter(employelist)
 
        // Set the LayoutManager that
        // this RecyclerView will use.
        val recyclerView:RecyclerView=view.findViewById(R.id.recycleView)
        recyclerView.layoutManager = LinearLayoutManager(context)
 
        // adapter instance is set to the
        // recyclerview to inflate the items.
        recyclerView.adapter = itemAdapter
    }
}


Java




package com.example.gfg;
 
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
public class FirstFragment extends Fragment {
    private String param1;
    private String param2;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            param1 = getArguments().getString("param1");
            param2 = getArguments().getString("param2");
        }
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first,
                                container, false);
    }
 
    public static FirstFragment newInstance(String param1,
                                            String param2)
    {
        FirstFragment fragment = new FirstFragment();
        Bundle args = new Bundle();
        args.putString("param1", param1);
        args.putString("param2", param2);
        fragment.setArguments(args);
        return fragment;
    }
 
    @Override
    public void onViewCreated(View view,
                              Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
 
        // getting the employeelist
        ArrayList<Employee> employelist
            = Constants.getEmployeeData();
 
        // Assign employeelist to ItemAdapter
        Adapter itemAdapter = new Adapter(employelist);
 
        // Set the LayoutManager that
        // this RecyclerView will use.
        RecyclerView recyclerView
            = view.findViewById(R.id.recycleView);
        recyclerView.setLayoutManager(
            new LinearLayoutManager(getContext()));
 
        // adapter instance is set to the
        // recyclerview to inflate the items.
        recyclerView.setAdapter(itemAdapter);
    }
}


Step 11: Working with MainActivity.kt

Navigate to the app > java >your package name > MainActivity, in this step we are going to setOnclickListener to the button and replace the FrameLayout with the Fragment.

Kotlin




package com.example.gfg
 
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
 
class MainActivity : AppCompatActivity() {
 
    // This method is called when the activity is first created
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // Get a reference to the "btn_frag" button from the layout
        val btn: Button = findViewById(R.id.btn_frag)
 
        // Set an OnClickListener on the button
        btn.setOnClickListener {
            // When the button is clicked, replace
            // the current fragment with a new
            // instance of the FirstFragment
            replaceFragment(FirstFragment())
 
            // Hide the button
            btn.visibility = View.GONE
        }
    }
 
    // This method replaces the current fragment
      // with a new fragment
    fun replaceFragment(fragment: Fragment) {
        // Get a reference to the FragmentManager
        val fragmentManager = supportFragmentManager
 
        // Start a new FragmentTransaction
        val fragmentTransaction = fragmentManager.beginTransaction()
 
        // Replace the current fragment with the new fragment
        fragmentTransaction.replace(R.id.frame_layout, fragment)
 
        // Commit the FragmentTransaction
        fragmentTransaction.commit()
    }
}


Java




package com.example.gfg;
 
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
 
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Get a reference to the "btn_frag" button from the
        // layout
        Button btn = findViewById(R.id.btn_frag);
 
        // Set an OnClickListener on the button
        btn.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v)
            {
                // When the button is clicked, replace
                // the current fragment with a new
                // instance of the FirstFragment
                replaceFragment(new FirstFragment());
 
                // Hide the button
                btn.setVisibility(View.GONE);
            }
        });
    }
 
    // This method replaces the current fragment
    // with a new fragment
    public void replaceFragment(Fragment fragment)
    {
        // Get a reference to the FragmentManager
        androidx.fragment.app
            .FragmentManager fragmentManager
            = getSupportFragmentManager();
 
        // Start a new FragmentTransaction
        androidx.fragment.app
            .FragmentTransaction fragmentTransaction
            = fragmentManager.beginTransaction();
 
        // Replace the current fragment with the new
        // fragment
        fragmentTransaction.replace(R.id.frame_layout,
                                    fragment);
 
        // Commit the FragmentTransaction
        fragmentTransaction.commit();
    }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads