Narendra Pal
Narendra Pal

Reputation: 6604

Open ViewPager2 to particular position without scrolling

I have implemented a recyclerview with some videos (say 10). Clicking on any item opens a viewpager2 which is on some other activity with all the items and the clicked one (from recyclerview) is shown. After that user can scroll to other item from there only. Everything is working fine.

Only the problem is with the scrolling when recyclerview item click where is the viewpager2 is opened.

Whenever any item is selected(10th). The viewpager opens first and the scroll itself to the (10th) position. I want to open 10th position of viewpager2 directly without scrolling. Any help would be appreciated.

I have tried setting the current item as

viewPagerReview.currentItem = recyclerviewItemSelectedPosition

but if the current item is last position of the recyclerview then viewpager also scrolls till last position.

Upvotes: 13

Views: 16240

Answers (2)

Surajkaran Meghwanshi
Surajkaran Meghwanshi

Reputation: 676

The correct solution for this problem follow this approach setCurrentItem(item :Int, smoothScroll : Boolean) viewPager.setCurrentItem( 2, false)

Upvotes: 0

Nizar
Nizar

Reputation: 2254

Alright, according to ViewPager2 on the AndroidDocs, this is what setCurrentItem(item: Int) would do:

Set the currently selected page. If the ViewPager has already been through its first layout with its current adapter there will be a smooth animated transition between the current item and the specified item.

Therefore, you're gonna want to use the other method, which is setCurrentItem(item: Int, smoothScroll: Boolean) in order to specify whether you want to smoothScroll or not.

So, in your case, go for:

viewPagerReview.setCurrentItem(recyclerviewItemSelectedPosition, false)

Upvotes: 36

Related Questions