Sticky item content in RecyclerView

338 views Asked by At

What is the best way to stick the content of a recyclerview items to the side of the screen. So that when the element goes off screen its content sticks to the side and goes with its parent only after there is no room in the rest of the element for that child.

I've attached the example where user scrolls left, so the red child of rv item is sticked to the left side of the screen.

result

1

There are 1 answers

1
Gobu CSG On BEST ANSWER

Try this code in your view holder

Kotlin

itemView.viewTreeObserver.addOnScrollChangedListener {
        val offset  = -itemView.left.toFloat()
        YOUR_RED_VIEW.translationX = offset.coerceAtLeast(0f)
//ELEVATION
        YOUR_RED_VIEW.translationZ = if (offset < 0) 2f else 0f
      
    }

Java

itemView.getViewTreeObserver().addOnScrollChangedListener(() -> {
        float offset = (float) -itemView.getLeft();
        YOUR_RED_VIEW.setTranslationX((float) Math.max(offset,0f));
        //ELEVATION
        YOUR_RED_VIEW.setTranslationZ(offset < 0 ? 2f : 0);
    });