Skip to main content

How to add dividers between items in a RecyclerView in Kotlin Android

How to add dividers between items in a RecyclerView in Kotlin Android.

Here's a detailed step-by-step tutorial on how to add dividers between items in a RecyclerView in Kotlin for Android:

Step 1: Set up your project

  • Create a new Android project in Kotlin.
  • Add the RecyclerView dependency to your app-level build.gradle file:
implementation 'androidx.recyclerview:recyclerview:1.2.0'

Step 2: Define the RecyclerView item layout

  • Create a new XML layout file for your RecyclerView item. For example, item_layout.xml.
  • Design the layout as per your requirements. Add any necessary views and styling.

Step 3: Create the RecyclerView adapter

  • Create a new Kotlin class called RecyclerViewAdapter.
  • Extend the RecyclerView.Adapter class and implement the necessary methods.
  • Pass the list of data items to the adapter constructor.
  • Inflate the item layout in the onCreateViewHolder method and return a ViewHolder object.
  • Bind the data to the views in the onBindViewHolder method.

Step 4: Set up the RecyclerView in your activity or fragment

  • Open your activity or fragment where you want to display the RecyclerView.
  • Add a RecyclerView widget to your layout XML file, for example:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
  • In your activity or fragment code, initialize the RecyclerView and set its layout manager and adapter. For example:
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
val layoutManager = LinearLayoutManager(this)
val adapter = RecyclerViewAdapter(dataList)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter

Step 5: Add dividers to the RecyclerView

  • Create a new XML layout file for the divider. For example, divider.xml.
  • Design the layout for the divider. It can be a simple view with a background color or a custom drawable.
  • In your activity or fragment code, create a DividerItemDecoration object and set it as the item decoration for the RecyclerView. For example:
val dividerItemDecoration = DividerItemDecoration(recyclerView.context, layoutManager.orientation)
dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider)!!)
recyclerView.addItemDecoration(dividerItemDecoration)

Note: Make sure to replace R.drawable.divider with the appropriate drawable resource for your divider.

Step 6: Run your app

  • Build and run your app on an Android device or emulator.
  • The RecyclerView should now display dividers between each item.

That's it! You have successfully added dividers between items in a RecyclerView in Kotlin for Android. You can customize the divider appearance by modifying the divider layout and drawable as per your design requirements.