2

I am trying to implement ViewPager2 with overlapping items (carousel like component). Everything seems fine, but my center item get overlapped by next item. I want my center item be in front of any neighbour items.

See image below:

enter image description here

When you use ViewPager1 class we can override getChildDrawingOrder

@Override
    protected int getChildDrawingOrder(int childCount, int i)

See example solution here: link

But ViewPager2 cannot be derived and extented (since ViewPager2 class is final). What should I do?

2 Answers2

1

Under the hood ViewPager2 contains a RecyclerView, so if you want to change the child drawing order you'll need to do it on the RecyclerView.

While it isn't an officially supported solution you can get access to the RecyclerView by asking for the first child on your view pager. See this comment:

https://issuetracker.google.com/issues/134912610#comment3

val recyclerView = viewPager2.getChildAt(0)

Once you have access to the RecyclerView you can add a ChildDrawingOrderCallback.

https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.ChildDrawingOrderCallback

The code below works if you have exactly 3 pages and want the middle page to be drawn on top of the other pages.

  recyclerView.setChildDrawingOrderCallback { childCount, i ->
        when (i) {
            0 -> 0
            1 -> 2
            2 -> 1
            else -> throw IllegalStateException("Expected 3 items")
        }
    }
Victor Rendina
  • 1,130
  • 12
  • 19
  • to support variable number of items I have implemented the 'setChildDrawingOrderCallback' as setChildDrawingOrderCallback { childCount, i -> IntArray(childCount) { it }.reversedArray()[i] } – ProjectDelta Dec 02 '20 at 00:27
0

After some research I finally decided to get rid of ViewPager2 and get back to ViewPager1 since I can override getChildDrawingOrder function, then I followed this answer to achieve what I actually wanted. Hope when ViewPager2 will be soon finalized and they will make ViewPager2 class non final

  • Checkout this repository i have added many `Transformation` for `Viewpager2` it will help you : https://github.com/askNilesh/Viewpager-Transformation – AskNilesh Jan 15 '20 at 05:14