Last active
September 12, 2017 20:04
-
-
Save ioxua/5f79724c1db301c0000f089909e2ac53 to your computer and use it in GitHub Desktop.
ItemDecoration for setting space around the RecyclerView items in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.graphics.Rect | |
import android.support.v7.widget.RecyclerView | |
import android.view.View | |
class PaddingItemDecoration(val paddingTop: Int = 0, | |
val paddingRight: Int = 0, | |
val paddingBottom: Int = 0, | |
val paddingLeft: Int = 0, | |
val affectFirst: Boolean = true, | |
val affectEveryoneElse: Boolean = false, | |
val affectLast: Boolean = false, | |
val paddingTopByHeight: Boolean = true, | |
val paddingBottomByHeight: Boolean = true) : RecyclerView.ItemDecoration() { | |
override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) { | |
if(view == null || parent == null) | |
return | |
val itemPosition = parent.getChildAdapterPosition(view) | |
if(itemPosition == RecyclerView.NO_POSITION) | |
return | |
if((affectFirst && itemPosition == 0) | |
|| (affectLast && itemPosition == parent.adapter.itemCount - 1) | |
|| (affectEveryoneElse && itemPosition != 0 && itemPosition != parent.adapter.itemCount - 1)) | |
setOffset(outRect, view) | |
} | |
internal fun setOffset(rect: Rect?, view: View?) { | |
val top = if(paddingTopByHeight) { | |
view?.height?: paddingTop | |
} else paddingTop | |
val bottom = if(paddingBottomByHeight) { | |
view?.height?: paddingBottom | |
} else paddingBottom | |
rect?.run { | |
this.top = top | |
this.bottom = bottom | |
this.right = paddingRight | |
this.left = paddingLeft | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment