How to use ItemDecoration for GridLayoutManager

How to use ItemDecoration for GridLayoutManager

By : user3042835
Date : November 29 2020, 12:01 PM
seems to work fine I would like to know how to add item decoration to have equal space between all items, and control whether to have space in each of the outer spaces
code :
import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.view.View
import androidx.annotation.DimenRes
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

class ItemOffsetDecoration(
    private val mItemOffset: Int,
    private val columnsSize: Int,
    private val includeEdges: EdgesIncluded
) : RecyclerView.ItemDecoration() {

    constructor(context: Context, @DimenRes itemOffsetId: Int, columnsSize: Int, includeEdges: EdgesIncluded) : this(

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        val lp = view.layoutParams as GridLayoutManager.LayoutParams
        val columnPosition = lp.spanIndex
        val isEven = columnPosition%2 == 0
        val isTopRow = lp.viewAdapterPosition < columnsSize
        val isBottomRow =
            if (parent.adapter == null)
                lp.viewAdapterPosition > parent.adapter!!.itemCount - columnsSize

        val left = if (isEven) mItemOffset/2 else mItemOffset
        val top = if (isTopRow) mItemOffset else mItemOffset/2
        val right = if (isEven) mItemOffset else mItemOffset/2
        val bottom = if (isBottomRow) mItemOffset else mItemOffset/2
            if (includeEdges.leftEdge) left else if (isEven) left else 0,
            if (includeEdges.topEdge) top else 0,
            if (includeEdges.rightEdge) right else if (isEven) 0 else right,
            if (includeEdges.bottomEdge) bottom else 0

    data class EdgesIncluded(
        val leftEdge: Boolean = true,
        val topEdge: Boolean = true,
        val rightEdge: Boolean = true,
        val bottomEdge: Boolean = true

Share : facebook icon twitter icon
RecyclerView different itemDecoration for different items

RecyclerView different itemDecoration for different items

By : Danny Brammel
Date : March 29 2020, 07:55 AM
this one helps. You can override RecyclerView.ItemDecoration#getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state), it is called for every visible child View view, you can get its position within the adapter by calling:
code :
Items are not the same width when using RecyclerView GridLayoutManager to make column spacing by ItemDecoration

Items are not the same width when using RecyclerView GridLayoutManager to make column spacing by ItemDecoration

By : sandeep
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I found the reason of the problem by myself. The offset that made in ItemDecoration is regarded as a part of item's dimensions(width and height)!
Let's take a look at the sample code and screen capture in the question above. The width of the screen capture is 480 pixels, and here is 3 columns, each item's width is 480/3 = 160 pixels. In SpacingDecoration, I add a left offset (20 pixels) on the first and second column, so the content's width of first and second column item is 160-20=140, then I add both left and right offset on the 3rd column item, so the content's width of 3rd column item is 160-20-20=120.
code :
spacing = 20
columnCount = 3
rowWidth = 480
itemWidth = rowWidth / columnCount
itemOccupiedSpacing = (spacing * (columnCount + 1)) / columnCount = spacing + spacing * (1/columnCount)
itemContentWidth = itemWidth - itemOccupiedSpacing

firstItemLeftOffset = spacing = spacing * (3/columnCount)
firstItemRightOffset = itemOccupiedSpacing - spacing = spacing * (1/columnCount)
secondItemLeftOffset = spacing - firstRightOffset = spacing * (2/columnCount)
secondItemRightOffset = itemOccupiedSpacing - secondLeftOffset = spacing * (2/columnCount)
thirdItemLeftOffset = itemOccupiedSpacing - secondLeftOffset = spacing * (1/columnCount)
thirdItemRightOffset = spacing = spacing * (3/columnCount)
itemLeftOffset = spacing * ((columnCount - colunmnIndex) / columnCount)
itemRightOffset = spacing * ((colunmnIndex + 1) / columnCount)
public class SpacingDecoration extends ItemDecoration {

    private int mHorizontalSpacing = 0;
    private int mVerticalSpacing = 0;
    private boolean mIncludeEdge = false;

    public SpacingDecoration(int hSpacing, int vSpacing, boolean includeEdge) {
        mHorizontalSpacing = hSpacing;
        mVerticalSpacing = vSpacing;
        mIncludeEdge = includeEdge;

    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        // Only handle the vertical situation
        int position = parent.getChildAdapterPosition(view);
        if (parent.getLayoutManager() instanceof GridLayoutManager) {
            GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
            int spanCount = layoutManager.getSpanCount();
            int column = position % spanCount;
            getGridItemOffsets(outRect, position, column, spanCount);
        } else if (parent.getLayoutManager() instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) parent.getLayoutManager();
            int spanCount = layoutManager.getSpanCount();
            StaggeredGridLayoutManager.LayoutParams lp = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
            int column = lp.getSpanIndex();
            getGridItemOffsets(outRect, position, column, spanCount);
        } else if (parent.getLayoutManager() instanceof LinearLayoutManager) {
            outRect.left = mHorizontalSpacing;
            outRect.right = mHorizontalSpacing;
            if (mIncludeEdge) {
                if (position == 0) {
                    outRect.top = mVerticalSpacing;
                outRect.bottom = mVerticalSpacing;
            } else {
                if (position > 0) {
                    outRect.top = mVerticalSpacing;

    private void getGridItemOffsets(Rect outRect, int position, int column, int spanCount) {
        if (mIncludeEdge) {
            outRect.left = mHorizontalSpacing * (spanCount - column) / spanCount;
            outRect.right = mHorizontalSpacing * (column + 1) / spanCount;
            if (position < spanCount) {
                outRect.top = mVerticalSpacing;
            outRect.bottom = mVerticalSpacing;
        } else {
            outRect.left = mHorizontalSpacing * column / spanCount;
            outRect.right = mHorizontalSpacing * (spanCount - 1 - column) / spanCount;
            if (position >= spanCount) {
                outRect.top = mVerticalSpacing;
ItemDecoration Before LayoutManager?

ItemDecoration Before LayoutManager?

By : Walmo Augusto Walmo
Date : March 29 2020, 07:55 AM
will be helpful for those in need Interesting question, but I don't believe it matters if you set the layout manager before or after the item decoration. Both calls result in a request for layout.
I am going to guess that you are adding the decoration to the RecyclerView more than one time. Since decorations compound, you will see a greater gap with the decoration added two times (or more times) instead of just once.
How to draw a view in an ItemDecoration?

How to draw a view in an ItemDecoration?

By : droogstore
Date : March 29 2020, 07:55 AM
I wish this help you Figured it out (Oops my bounty)
In order for a View to be created correctly, it needs 3 steps:
code :
private fun initHeader(parent: RecyclerView?) {
    if (header == null) {
        val view = parent?.context?.inflate(R.layout.decoration, parent, false)
        val bitmap = Bitmap.createBitmap(parent?.width?:0, 40.dp(), Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        val widthSpec = View.MeasureSpec.makeMeasureSpec(parent?.width ?: 0, View.MeasureSpec.EXACTLY)
        val heightSpec = View.MeasureSpec.makeMeasureSpec(40.dp(), View.MeasureSpec.EXACTLY)
        view?.measure(widthSpec, heightSpec)
        view?.layout(0, 0, parent.width, 40.dp())
        header = bitmap
How to set ItemDecoration only for certain ViewType?

How to set ItemDecoration only for certain ViewType?

By : kahseong
Date : December 23 2020, 07:01 PM
With these it helps Problem
My mistake consists of the conviction to use ItemDecoration in order to set custom dividers for different ViewType. I have developed a clear belief that such a custom dividers should do only ItemDecoration.
code :
<LinearLayout ...>

    <TextView ... />

    <!-- This -->
    <View style="@style/DividerStyle" />

<style name="DividerStyle">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">@dimen/dividerHeight</item>
    <item name="android:background">@android:color/black</item>
Related Posts Related Posts :
  • List<String>- Null
  • How to normalize channel values to the range[0.0,1.0]?
  • How to convert a signed APK to an unsigned APK
  • Android library AAR packing resource incorrectly
  • Why it fail to upload apk to google play console?
  • How do I get more than 500 contact lists on Android?
  • Android layer-list affecting position of floating action button
  • Koin: NoBeanDefFoundException, Check your module definitions
  • Jetpack Navigation: Hide label in toolbar
  • get thumbnail from video URL but it takes more than 5 seconds to load data on recycler view
  • How to fix 'Android SDK not found at this location' error while installing flutter?
  • Android Shared Storage protection issue
  • How can I clone views using java code in Android Studio
  • Hide title and action bar for splash screen and remove White screen in start
  • Why can not hashing key android for facebook
  • Can not create handler inside thread that has not called Looper.prepare()
  • ID of the child views in a custom view are same in Android
  • Android: unable to hide appbar on scrolling
  • Best layout for form-style screen
  • How To create multiple function in Adapter Class Android with Retrofit
  • Can the Android Flow virtual layout handle variable-width Views
  • How to fix "Unable to load class 'dagger.Multibindings'" due to problems with gradle
  • VpnService always-on "not supported by this app"
  • Android Studio - Gradle "Sync now" is not Available
  • How do i get my code to give my current location?
  • Could not initialize class sun.util.calendar.ZoneInfoFile while using Flutter firebase-notifications
  • How to implement circular to check / tick animation in Android?
  • Toolbar shadow not showing
  • Android Sqlite get rows where first character is not an Alphabet
  • why I receive "bad request" in my request by retrofit
  • Intercept NavigationUI.onNavDestinationSelected() to make backstack pop with "inclusive = true"
  • I have a problem with the navigation fragments in my proyect, it sais that I need a defaut nav host atribute but I alrea
  • How can I keep a BottomSheetDialogFragment height to always match_parent?
  • How to reference a timerPicker in android studio using kotlin
  • Firebase Crashlytics - get stacktrace info to display during CrashlyticsListener.crashlyticsDidDetectCrashDuringPrevious
  • Schedule a repeating alarm clock
  • Can't assign values outside onTouchListener
  • Is setContentView() needed to inflate a fragment?
  • Why instead of string method returns Kotlin.Unit?
  • Retrofit slash as Query
  • When does onCreateView() get called in this app?
  • Fragment is reloaded each time after rejecting location permission
  • How to read ViewModel data from sttrings.xml list of items
  • Flutter doctor does not see vs code ,VS code does not detect flutter/bin
  • How to build aar in flutter
  • Gradle Build Fails - Illegal exception table range in class file com/google/wireless/android/sdk/stats/GradleBuildMemory
  • register has type Long (High Half) but expected Long (Low Half)
  • Is it good idea to use Dispatcher.Main with delay( )?
  • WebView and Advanced View is Not loading partiucalr URL
  • How to show three dots at the end of text view
  • Is it possible to run macros within Android Studio project?
  • Adding a button with default appearance but changed background color
  • What is best way to show notification at a certain time in Android?
  • Jetifier not working when library uses android component and app uses androidx component
  • How can I write the contents of an image in a filesystem
  • Retrieve a list of images from the Database and display them using a ListView?
  • java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
  • Timer/hourglass wont stop
  • How can I make AndroidX the default library for new Android projects?
  • Is it okay to delete buildToolsVersion android studio because of a warning in the Asyncstorage library?
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org