Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager2 default position

I'm creating a slideshow with ViewPager2. For example, the slideshow has 3 items and I want to show the second item when the activity opens. I use setCurrentItem(int item, boolean smoothScroll) method but it doesn't work and nothing happens. How can I achieve it?

viewPager.adapter = adapter viewPager.setCurrentItem(1, true) 
like image 226
hosseinAmini Avatar asked May 26 '19 08:05

hosseinAmini


People also ask

What is the difference between ViewPager and ViewPager2?

ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .

How do I refresh ViewPager2?

As we already know that ViewPager2 is built on RecyclerView that's why it's easy to update only one item by calling the method notifyItemChanged(index). If we want to update all items then we can also do this by simply calling the notifyDatasetChanged() method. That's it for now.

How do you use TabLayoutMediator?

Establish the link by creating an instance of this class, make sure the ViewPager2 has an adapter and then call attach() on it. Instantiating a TabLayoutMediator will only create the mediator object, attach() will link the TabLayout and the ViewPager2 together.


2 Answers

I think an easier more reliable fix is to defer to next run cycle instead of unsecure delay e.g

viewPager.post {   viewPager.setCurrentItem(1, true) } 
like image 64
Rune Avatar answered Sep 22 '22 14:09

Rune


setCurrentItem(int item, boolean smoothScroll) works correctly in ViewPager but in ViewPager2 it does not work as expected. Finally, I faced this problem by adding setCurrentItem(int item, boolean smoothScroll) method into a delay like this:

Handler().postDelayed({      view.viewPager.setCurrentItem(startPosition, false) }, 100) 
like image 30
hosseinAmini Avatar answered Sep 20 '22 14:09

hosseinAmini