3

I had a RecyclerView configured with various Extension Functions to center and see the next item:

fun RecyclerView.pageSnap() = this.post {
    if (this.onFlingListener == null) PagerSnapHelper().attachToRecyclerView(this)
}

fun RecyclerView.snapCenterWithMargin(left: Int, top: Int, right: Int, bottom: Int) {
    val offsetItemDecoration = SnapCenterWithMargin(left, top, right, bottom)
    this.addItemDecoration(offsetItemDecoration)
}

private class SnapCenterWithMargin(
    private val left: Int,
    private val top: Int,
    private val right: Int,
    private val bottom: Int
) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        view.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        val position = parent.getChildAdapterPosition(view)
        val firstItem = 0
        val lastItem = state.itemCount - 1
        when (position) {
            firstItem -> {
                val firstPadding = (parent.width) / 2 - view.measuredWidth / 2
                outRect.set(firstPadding, 0, 0, 0)
            }
            lastItem -> {
                val lastPadding = (parent.width) / 2 - view.measuredWidth / 2
                outRect.set(0, 0, lastPadding, 0)
            }
            else -> {
                outRect.set(left, top, right, bottom)
            }
        }
    }

}

The problem is the ListAdapter animations are bad with this approach. Then I tried to move to ViewPager2 but I can't get this behavior (see the next screen and keep items centered).

JavierSegoviaCordoba
  • 6,531
  • 9
  • 37
  • 51
  • I don't understand what you are trying to achieve. I've explained how you can show the previous and next item on a `ViewPager2` here: https://stackoverflow.com/a/58191654/4034572. Is that what you want? – Albert Vila Calvo Oct 01 '19 at 20:24
  • 3
    How can I know if that post if for viewpager 2 if there is 0 mentions to it as viewpager 2 – JavierSegoviaCordoba Oct 01 '19 at 20:26

1 Answers1

1

Layout of the page item:

android:paddingStart="24dp"
android:paddingEnd="24dp"

ViewPager2 in code:

viewPager2.setClipToPadding(false);
viewPager2.setOffscreenPageLimit(2);
viewPager2.setPageTransformer(new ViewPager2.PageTransformer()
{
    @Override
    public void transformPage(@NonNull View page, float position)
    {
        float offset = (int)ScreenUtils.dpToPx(48) * position;
        page.setTranslationX(-offset);
    }
});
M.Paunov
  • 1,737
  • 1
  • 15
  • 19