Search code examples
androidandroid-recyclerviewgridlayoutmanager

GridLayoutManager with custom divider


I am trying to add custom divider in RecyclerView with GridLayoutManager but not getting success, i have searched a lot and looked into below mention answer but it didn't help me

link 1
link 2
link 3

I want to put black line in between each items of RecyclerView, something like below.

enter image description here

I have got horizontal line in between each row, but not able to find how to get those lines in between columns also.

chintan soni's answer worked perfectly, but it is creating problem in one scenario only, when i am having 5 views, it shows divider of other 3 items also, like below :

enter image description here


Solution

  • Check this out: https://bignerdranch.github.io/simple-item-decoration/

    Add this to your app level gradle and sync:

    compile 'com.bignerdranch.android:simple-item-decoration:1.0.0'
    

    Then, apply code as below:

        Drawable horizontalDivider = ContextCompat.getDrawable(this, R.drawable.line_divider);
        Drawable verticalDivider = ContextCompat.getDrawable(this, R.drawable.line_divider);
        recyclerView.addItemDecoration(new GridDividerItemDecoration(horizontalDivider, verticalDivider, 4));
    

    My line_divider.xml was as follows:

    <?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="@android:color/black" />
    
    </shape>
    

    This is just a quick answer from me. But this should work, I guess..

    Output:enter image description here