How to Implement RecyclerView in a Fragment in Android?
Last Updated :
06 Apr, 2023
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 :
- Create a RecyclerView layout
- Create a RecyclerView Adapter
- Set the RecyclerView Adapter and LayoutManager in our fragment onCreateView method
- 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
android:id = "@+id/llMain"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center_vertical"
android:orientation = "horizontal"
android:padding = "10dp" >
< 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
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:padding = "15dp"
android:orientation = "vertical" >
< 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
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" ?>
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
tools:context = ".FirstFragment" >
< LinearLayout
android:orientation = "vertical"
android:layout_width = "match_parent"
android:layout_height = "match_parent" >
< 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" />
< 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" ?>
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
android:id = "@+id/llMain"
tools:context = ".MainActivity" >
< FrameLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:id = "@+id/frame_layout" >
< 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,
val email:String
):java.io.Serializable
|
Java
package com.example.gfg;
import java.io.Serializable;
public class Employee implements Serializable {
private final String name;
private final String email;
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 {
fun getEmployeeData():ArrayList<Employee>{
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 {
public static ArrayList<Employee> getEmployeeData()
{
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>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.items_list, parent, false )
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return emplist.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentEmp = emplist[position]
holder.name.text = currentEmp.name
holder.email.text = currentEmp.email
}
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;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_list, parent, false );
return new MyViewHolder(itemView);
}
@Override
public int getItemCount() {
return emplist.size();
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Employee currentEmp = emplist.get(position);
holder.name.setText(currentEmp.getName());
holder.email.setText(currentEmp.getEmail());
}
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)
val employelist=Constants.getEmployeeData()
val itemAdapter=Adapter(employelist)
val recyclerView:RecyclerView=view.findViewById(R.id.recycleView)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = itemAdapter
}
|
Java
@Override
public void
onViewCreated( @NonNull View view,
@Nullable Bundle savedInstanceState)
{
super .onViewCreated(view, savedInstanceState);
ArrayList<Employee> employelist
= Constants.getEmployeeData();
Adapter itemAdapter = new Adapter(employelist);
RecyclerView recyclerView
= view.findViewById(R.id.recycleView);
recyclerView.setLayoutManager(
new LinearLayoutManager(getContext()));
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
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() {
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? {
return inflater.inflate(R.layout.fragment_first, container, false )
}
companion object {
@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)
val employelist=Constants.getEmployeeData()
val itemAdapter=Adapter(employelist)
val recyclerView:RecyclerView=view.findViewById(R.id.recycleView)
recyclerView.layoutManager = LinearLayoutManager(context)
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)
{
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);
ArrayList<Employee> employelist
= Constants.getEmployeeData();
Adapter itemAdapter = new Adapter(employelist);
RecyclerView recyclerView
= view.findViewById(R.id.recycleView);
recyclerView.setLayoutManager(
new LinearLayoutManager(getContext()));
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() {
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btn: Button = findViewById(R.id.btn_frag)
btn.setOnClickListener {
replaceFragment(FirstFragment())
btn.visibility = View.GONE
}
}
fun replaceFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.frame_layout, fragment)
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);
Button btn = findViewById(R.id.btn_frag);
btn.setOnClickListener( new View.OnClickListener() {
@Override public void onClick(View v)
{
replaceFragment( new FirstFragment());
btn.setVisibility(View.GONE);
}
});
}
public void replaceFragment(Fragment fragment)
{
androidx.fragment.app
.FragmentManager fragmentManager
= getSupportFragmentManager();
androidx.fragment.app
.FragmentTransaction fragmentTransaction
= fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout,
fragment);
fragmentTransaction.commit();
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...