Android – How to Change the Color of Alternate Rows in RecyclerView
RecyclerView is an essential ViewGroup used in Android to display a list of items. It provides a flexible and highly customizable way of implementing a list that can be presented as a grid or a list. In this project, we will be working with RecyclerView to change the color of alternate rows. Typically, all items in a RecyclerView have the same color, which can be monotonous and unappealing. By alternating the row colors, we can provide a better visual experience to the user. To achieve this, we will assign a LightGrey color to the items at even positions and a White color to those at odd positions. This simple trick will help us customize our RecyclerView and enhance the user interface. The image below illustrates what we will accomplish in this project.
.jpg)
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: Add buildFeatures to build.gradle (Module:app)
Since in this project, we used ViewBinding so we have to set ViewBinding=True. Navigate to Gradle Scripts > build.gradle (Module:app) and add the Below buildFeatures section under the android section in the build.gradle (Module:app).
buildFeatures { viewBinding = true }
Android Section
android { namespace 'com.example.geeksforgeeks' compileSdk 32 defaultConfig { applicationId "com.example.geeksforgeeks" minSdk 21 targetSdk 32 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } buildFeatures { viewBinding = true } }
After adding this buildFeatures section, Sync the Project.
Step 3: 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 4: 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. Below is the code for the activity_main.xml file. The activity_main.xml represents the UI part of our application. It includes one RecyclerView on which our list of items is displayed. Comments are added inside the code for a better understanding of the Code.
XML
<? xml version = "1.0" encoding = "utf-8" ?> <!--Here we Used ConstraintLayout for our project --> < androidx.constraintlayout.widget.ConstraintLayout android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > <!--RecyclerView --> < androidx.recyclerview.widget.RecyclerView android:layout_width = "match_parent" android:layout_height = "match_parent" android:id = "@+id/rvItemsList" /> </ androidx.constraintlayout.widget.ConstraintLayout > |
Step 5: Creating a layout for RecyclerView
Here we have to create a layout for our RecyclerView to display our items. Navigate to app > res > layout then Create a new layout resource file and name it items_row.xml. It includes three Text Views for displaying the Name and Emails of the Employees. Comments are added inside the code for a better understanding of the Code.
items_row.xml:
XML
<? xml version = "1.0" encoding = "utf-8" ?> <!--LinearLayout orientation horizontal --> < 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" > <!--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 ":" --> < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = " : " android:textSize = "20dp" android:textStyle = "bold" /> <!--TextView for displaying Email --> < TextView android:id = "@+id/tvEmail" android:layout_width = "0dp" android:layout_height = "wrap_content" android:layout_weight = "1" android:textColor = "#454545" android:textSize = "16sp" tools:text = "Email" /> </ LinearLayout > |
Step 6: Creating 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.
Employee.kt:
Kotlin
package com.example.geeksforgeeks // Employee model data class Employee( val name:String, // name of the employee val email:String // email of the employee ) |
Java
package com.example.geeksforgeeks; // Employee model public class Employee { private String name; // name of the employee private 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; } public void setName(String name) { this .name = name; } public void setEmail(String email) { this .email = email; } } |
Step 7: Creating Employee ArrayList
In this step, we are going to prepare the List 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.
Constants.kt:
Kotlin
package com.example.geeksforgeeks object Constants { // This Method create an employee // 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) return employeeList } } |
Java
package com.example.geeksforgeeks; import java.util.ArrayList; public class Constants { // This Method create an employee // 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); return employeeList; } } |
Step 8: Creating Adapter for our RecyclerView
As we know for every RecycleView we need an Adapter class. and Implement the Three member functions.
- onCreateViewHolder: Here we have to connect the layout resource file that we are for our RecyclerView.
- onBindViewHolder: Here we have to bind our items to the data source.
- getItemCount: Here we have to return the length of our ArrayList
Here we are going to implement the main logic to change the color of the alternate Row item. In the onBindViewHolder method we are going to check if the position is Even we assign Light grey color to that item and if the position is odd then we going to assign a white color to the item.
if (position % 2 == 0) { holder.llMain.setBackgroundColor( ContextCompat.getColor( holder.itemView.context, R.color.colorLightGray ) ) } else { holder.llMain.setBackgroundColor(ContextCompat.getColor(context, R.color.colorWhite)) }
Navigate to app > java >your package name > Create a Kotlin Object named as ItemAdapter.Below is the code for the ItemAdapter class. Comments are added inside the code for a better understanding of the Code.
ItemAdapter.kt:
Kotlin
package com.example.geeksforgeeks import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.example.geeksforgeeks.databinding.ItemsRowBinding class ItemAdapter( private val items: ArrayList<Employee> ) : RecyclerView.Adapter<ItemAdapter.ViewHolder>() { // Inflates the item views which is designed in xml layout file // create a new // ViewHolder and initializes some private fields to be used by RecyclerView. override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( ItemsRowBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } // Binds each item in the ArrayList to a view // Called when RecyclerView needs a new {@link ViewHolder} // of the given type to represent // an item. // This new ViewHolder should be constructed with a new // View that can represent the items // of the given type. You can either create a new // View manually or inflate it from an XML // layout file override fun onBindViewHolder(holder: ViewHolder, position: Int) { val context = holder.itemView.context val item = items[position] holder.tvName.text = item.name holder.tvEmail.text = item.email // Updating the background color according // to the odd/even positions in list. if (position % 2 == 0 ) { holder.llMain.setBackgroundColor( ContextCompat.getColor( holder.itemView.context, R.color.colorLightGray ) ) } else { holder.llMain.setBackgroundColor(ContextCompat.getColor(context, R.color.colorWhite)) } } // Gets the number of items in the list override fun getItemCount(): Int { return items.size } // A ViewHolder describes an item view and metadata // about its place within the RecyclerView. class ViewHolder(binding: ItemsRowBinding) : RecyclerView.ViewHolder(binding.root) { // Holds the TextView that // will add each item to val llMain = binding.llMain val tvName = binding.tvName val tvEmail = binding.tvEmail } } |
Java
package com.example.geeksforgeeks; import android.content.Context; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import com.example.geeksforgeeks.databinding.ItemsRowBinding; import java.util.ArrayList; public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> { private ArrayList<Employee> items; public ItemAdapter(ArrayList<Employee> items) { this .items = items; } // Inflates the item views which is designed in xml layout file // create a new // ViewHolder and initializes some private fields to be used by RecyclerView. @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder( ItemsRowBinding.inflate( LayoutInflater.from(parent.getContext()), parent, false ) ); } // Binds each item in the ArrayList to a view // Called when RecyclerView needs a new {@link ViewHolder} // of the given type to represent // an item. // This new ViewHolder should be constructed with a new // View that can represent the items // of the given type. You can either create a new // View manually or inflate it from an XML // layout file @Override public void onBindViewHolder(ViewHolder holder, int position) { Context context = holder.itemView.getContext(); Employee item = items.get(position); holder.tvName.setText(item.getName()); holder.tvEmail.setText(item.getEmail()); // Updating the background color according // to the odd/even positions in list. if (position % 2 == 0 ) { holder.llMain.setBackgroundColor( ContextCompat.getColor( holder.itemView.getContext(), R.color.colorLightGray ) ); } else { holder.llMain.setBackgroundColor(ContextCompat.getColor(context, R.color.colorWhite)); } } // Gets the number of items in the list @Override public int getItemCount() { return items.size(); } // A ViewHolder describes an item view and metadata // about its place within the RecyclerView. public static class ViewHolder extends RecyclerView.ViewHolder { // Holds the TextView that // will add each item to private final ViewGroup llMain; private final TextView tvName; private final TextView tvEmail; public ViewHolder(ItemsRowBinding binding) { super (binding.getRoot()); llMain = binding.llMain; tvName = binding.tvName; tvEmail = binding.tvEmail; } } } |
Step 9: Working with MainActivity File
In this step, we are going to Get the employeelist by calling the Constants getEmployeeData() method and assign the employee list to the ItemAdapter and display the employee list.
MainActivity.kt:
Kotlin
package com.example.geeksforgeeks import android.Manifest import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.core.app.ActivityCompat import androidx.recyclerview.widget.LinearLayoutManager import com.example.geeksforgeeks.databinding.ActivityMainBinding // In this project we are going to use view binding class MainActivity : AppCompatActivity() { // View Binding var binding:ActivityMainBinding?= null override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) binding=ActivityMainBinding.inflate(layoutInflater) setContentView(binding?.root) // getting the employeelist val employelist=Constants.getEmployeeData() // Assign employeelist to ItemAdapter val itemAdapter=ItemAdapter(employelist) // Set the LayoutManager that // this RecyclerView will use. binding?.rvItemsList?.layoutManager = LinearLayoutManager( this ) // adapter instance is set to the // recyclerview to inflate the items. binding?.rvItemsList?.adapter = itemAdapter } } |
Java
package com.example.geeksforgeeks; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.recyclerview.widget.LinearLayoutManager; import android.Manifest; import android.os.Bundle; import android.widget.Toast; import com.example.geeksforgeeks.databinding.ActivityMainBinding; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // View Binding private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // getting the employeelist ArrayList<Employee> employelist = Constants.getEmployeeData(); // Assign employeelist to ItemAdapter ItemAdapter itemAdapter = new ItemAdapter(employelist); // Set the LayoutManager that this RecyclerView will use. binding.rvItemsList.setLayoutManager( new LinearLayoutManager( this )); // adapter instance is set to the recyclerview to inflate the items. binding.rvItemsList.setAdapter(itemAdapter); } } |
Output:
Please Login to comment...