How to apply ItemDecoration from left and right side both to RecyclerView item?

只谈情不闲聊 提交于 2021-01-27 07:34:52

问题


I have been trying to achieve this for so long. What I want is to overlap the selected RecyclerView item from left and right as shown in the picture below.

I'm able to achieve left or right by ItemDecoration like below:

class OverlapDecoration(private val overlapWidth:Int) : RecyclerView.ItemDecoration() {
    private val overLapValue = -40

    val TAG = OverlapDecoration::class.java.simpleName

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {

        val itemPosition = parent.getChildAdapterPosition(view)

        if (itemPosition == 0) {
            return
        } else {
            outRect.set(overLapValue, 0, 0, 0)
        }
    }
}

I have achieved like below image so far.

I have already tried with CarouselLayoutManager but it not what I'm looking for.


回答1:


To achieve the result you're looking for you need to take two steps:

First, to correct the decorator calculations:

if (itemPosition == 0) {
    return
} else {
    outRect.set(-1 * overLapValue, 0, overLapValue, 0) //Need left, AND right
}

Second, you need to actually add the shadow

And, one quick bit of cleanup for the class, you don't need the private val overLapValue.

Instead:

class OverlapDecoration(private val overlapWidth:Int = 40) : RecyclerView.ItemDecoration() {


来源:https://stackoverflow.com/questions/52039853/how-to-apply-itemdecoration-from-left-and-right-side-both-to-recyclerview-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!