Android RecyclerView With Item Divider

RecyclerView is a ViewGroup ,that display a scrolling list of elements based on large data sets (or data that frequently changes). RecyclerView widget is more flexible and efficient version of  ListView .

In the previous tutorial we have seen basic example of recyclerView and recyclerView item click , In this tutorial we will see how to add divider to item of recyclerView .



Project Detail
Project Name RecyclerView
Package com.tutorialsbuzz.recyclerview
Min Sdk Version 22
Target Sdk Version 29
Compile Sdk Version 29
Theme Theme.AppCompat.Light.DarkActionBar

Adding RecyclerView To Layout  



file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rcv"/>

Adapter and ViewHolder For RecyclerView .


1. XML Layout for RecyclerView Item : 

file : row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:padding="20dp"
        android:layout_height="wrap_content">
    
    <TextView
            android:id="@+id/txt"
            android:textSize="22sp"
            android:text="Title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="bold"/>

    <TextView
            android:id="@+id/sub_txt"
            android:textSize="18sp"
            android:text="Title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="italic"/>

</LinearLayout>

2. Data class : 

We will read json file kept inside asset folder and map it data class .

find the data class at github code repo
https://github.com/TutorialsBuzz/RecyclerViewItemDivider/blob/master/app/src/main/java/com/tutorialsbuzz/recyclerview/Model.kt

3. Adapter and Viewholder :

find the Adapter and viewholder class at github code repo
https://github.com/TutorialsBuzz/RecyclerViewItemDivider/blob/master/app/src/main/java/com/tutorialsbuzz/recyclerview/CustomAdapter.kt

Divider For RecyclerView Items (ItemDecortion)


An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter's data set. This can be useful for drawing dividers between items of recyclerView .

Create a rectangle shape drawable , set its width , height and set color .(This drawable is added between items of recyclerView)

file : line_divider.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <size
            android:width="1dp"
            android:height="1dp"/>

    <solid android:color="@color/dividerColor"/>

</shape>

Create a class SimpleDividerItemDecoration and extend it to ItemDecoration . Inside onDrawOver function draw the above defined drawable using canvas object .

file : SimpleDividerItemDecoration.kt
package com.tutorialsbuzz.recyclerview

import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView

class SimpleDividerItemDecoration : RecyclerView.ItemDecoration {
    private var mDivider: Drawable? = null

    constructor(context: Context) {
        mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider)
    }

    constructor(context: Context, drawable: Int) {
        mDivider = ContextCompat.getDrawable(context, drawable)
    }

    override fun onDrawOver(c: Canvas, recyclerView: RecyclerView, state: RecyclerView.State) {
        
        val left = recyclerView.paddingLeft
        val right = recyclerView.width

        val childCount = recyclerView.childCount
        for (i in 0 until childCount) {

            val child = recyclerView.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            val top = child.bottom + params.bottomMargin
            val bottom = top + mDivider!!.intrinsicHeight
            mDivider!!.setBounds(left, top, right, bottom)
            mDivider!!.draw(c)

        }
    }
}

 Adding CustomItemDecortion to recyclerView .

To add ItemDecorator call addItemDecoration using recyclerView reference and pass the instance of above defined SimpleDividerItemDecoration

rcv.addItemDecoration(SimpleDividerItemDecoration(this))

Activity


  1. Create a koltin class MainActivity.kt and extend it to AppCompatActivity class .
  2. Override onCreate function and set the content of this MainActivity with above defined xml layout (activity_main.xml). 
  3. Read JSON Data From Asset Folder , this will be used for binding data into recyclerView .
  4. Set Vertical Linear LayoutManager to RecyclerView.
  5. Create Instance of Adapter and set to RecyclerView .
  6. Add CustomItemDecortion to RecyclerView .

file : MainActivity.kt
package com.tutorialsbuzz.recyclerview

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONArray
import org.json.JSONObject

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val model = readFromAsset();
        val adapter = CustomAdapter(model, this)
        rcv.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        rcv.adapter = adapter;
        rcv.addItemDecoration(SimpleDividerItemDecoration(this))
    }


    private fun readFromAsset(): List<Model> {
        val modeList = mutableListOf<Model>()
        val bufferReader = application.assets.open("android_version.json").bufferedReader()
        val json_string = bufferReader.use {
            it.readText()
        }

        val jsonArray = JSONArray(json_string);
        for (i in 0..jsonArray.length() - 1) {
            val jsonObject: JSONObject = jsonArray.getJSONObject(i)
            val model = Model(jsonObject.getString("name"), jsonObject.getString("version"))
            modeList.add(model)
        }
        return modeList
    }

}


No comments:

Post a Comment