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)
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)
}
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)
Do not use timers, you will run into a lot of probable states in which the user has a slow phone and it actually takes a lot longer than 100 ms to run, also, you wouldn't want too slow of a timer making it ridiculously un-reliable.
Below we do the following, we set a listener to our ViewTreeObserver and wait until a set number of children have been laid out in our ViewPager2's RecyclerView (it's inner working). Once we are sure x number of items have been laid out, we start our no-animation scroll to start at the position.
val recyclerView = (Your ViewPager2).getChildAt(0)
recyclerView.apply {
val itemCount = adapter?.itemCount ?: 0
if(itemCount >= #(Position you want to scroll to)) {
viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
// False for without animation scroll
(Your ViewPager2).scrollToPosition(#PositionToStartAt, false)
}
}
}
First off, I think that the accepted answer shouldn't be #hosseinAmini 's, since it's suggesting to use a delay to work around the problem. You should first be looking for what the assumed bug is caused by, rather than trusting unreasonable solutions like that.
#Rune's proposal is correct, instead; so I'm quoting their code in my answer:
viewPager.post {
viewPager.setCurrentItem(1, true)
}
The only thing I'd argue about is the aforementioned one's belief that their solution is just deferring the execution of that lambda in the next run cycle. This wouldn't make anything buggy work properly. Rather, what it is actually being done is deferring the execution of that lambda to once the view has been attached to a window, which implies it's also been added to a parent view. Indeed, there looks to be an issue as to changing the current ViewPager2 item before being attached to a window. Some evidence to support this claim follows:
Using whichever Handler won't work nearly as effectively.
Handler(Looper.getMainLooper()).post {
viewPager.setCurrentItem(1, true) // Not working properly
}
From a theoretical standpoint, it might incidentally work due to the ViewPager2 being attached to a window acquiring priority in the message queue of the main looper, but this shouldn't ever be relied upon as there's just no guarantee that it'll work (it's even more likely it won't) and if it even turned out to be working, further investigation running multiple tests should make my point clear.
View.handler gets null, which means the view hasn't been attached to any window yet.
View.handler // = null
Despite Android UI being tied to the main looper, which will always uniquely correspond to the main thread –hence also called the UI thread,– a weird design choice stands in the handler not being associated to each view until they get attached to a window. A reason why this may lay on the consequent inability of views to schedule any work on the main thread while they're not part of the hierarchy, which may turn useful when implementing a view controller that schedules view updates while unaware of their lifecycle (in which case it would employ the View's handler, if any — or just skip scheduling whatever it was going to if none).
EDIT:
Also, #josias has pointed out in a comment that it'd be clearer to use:
viewPager.doOnAttach {
viewPager.setCurrentItem(1, true)
}
Thanks for that suggestion! It expresses better the actual intent, rather than relying on the behavior of the View.post method.
Do not use timers and all that stuff with 'post', it's not the reliable solution and just a piece of code that smells.
Instead, try use viewPager.setCurrentItem(1, false). That 'false' is about smoothScroll, you can't smooth scroll your viewPager2 when your activity is just opened. Tested it on a fragment in onViewCreated() method, it also didn't work with "true", but works with "false"
As it was mentioned above you have to use setCurrentItem(position, smoothScroll) method on ViewPager2 in order to show selected item. To make it work you have to define a callback, here is an example:
ViewPager2.OnPageChangeCallback callback = new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
}
};
And then you have to register it as follow:
viewPager.registerOnPageChangeCallback(callback);
Also do not forget to unregister it:
viewPager.unregisterOnPageChangeCallback(callback);
When you call setCurrentItem(position) method it will call onPageSelected(int position) method from your callback passing your argument, and then method createFragment(int position) from FragmentStateAdapter class will be called to show your fragment.
I tried changing viewpager2 page in Handler().dely() and viewPager2.post{} and even 'viewPager2.get(0).post all didn't work for me, I'm using ViewPager with FragmentStateAdapter with Tablayout.
What worked for me is changing the position of the RecylerView in ViewPager2 after binding FragmentStateAdapter to yourViewPager2View.adapter manually:
(yourViewPager2View[0] as RecyclerView).scrollToPosition(moveToTabNumber)
Why
My problem is onCreateFragment(position:Int):Fragmeet function in FragmentStateAdapter always starting fragment at 0 position no matter what pageNumber I set the page
viewPager.setCurrentItem = pageNumber
I checked where it's called in FragmentStateAdapter it's called in FragmentStateAdapter:
onBindViewHolder(final #NonNull FragmentViewHolder holder, int position)`
so all I needed is to force onBindViewHolder to call onCreateFragment(position:Int) with the page number I wanted.
mViewPager.setCurrentItem(1, true); ---> this is sufficient as you written above
That should work,
in doubt, just check your position:
#Override
public void onPageSelected(int i) {
if (LOG_DEBUG) Log.v(TAG, " ++++++++ onPageSelected: " + i);
mViewPager.setCurrentItem(i);
//TODO You can use this position: to write other dependent logic
}
and also check
getItem(int position) in PagerAdapter
or else paste your code.
I noticed that it works fine when the view is initially created if you opt to not animate it.
viewPager2.setCurrentItem(index, false)
This is usually fine depending on your use case - this initial/default item probably doesn't need to be animated in.
I met the same problem. In my case, I make the viewPager2 Gone by default until network requests succeed, I fix it by setting the CurrentItem after I make the viewPager2 visible.
My answer may not be helpful now but i see no harm to post my expreince, i just came to this problem using ViewPager and ViewPager2 and unexpectedly solved it by just changing some line codes order.
Here is (java) solution for ViewPager:
reviewWordViewPager.addOnPageChangeListener(changeListener);
reviewWordViewPager.setCurrentItem(viewPosition, true/false);
reviewWordTabIndicator.setupWithViewPager(reviewWordViewPager, true);
(Java) solution for ViewPager2:
wordViewPager.registerOnPageChangeCallback(viewPager2OnPageChangeCallback);
wordViewPager.setCurrentItem(vpPosition, true/false);
new TabLayoutMediator(tabIndicator, wordViewPager,
((tab, position) -> tab.setText(viewPagerTitle[position]))).attach();
I did not look up for ViewPager2 whether it needs the following old code used in ViewPager
#Override
public int getItemPosition(#NonNull Object object) {
// refresh all fragments when data set changed
return POSITION_NONE;
}
But surprisingly no need for it in ViewPager2 to solve the problem i've been having, hope it helps others
In case you use context.startActivity to start new activities no need to use wordViewPager.setCurrentItem(item, smoothScroll) in your onResume function to get back to the last selected tab before you started new activity you just save ViewPager/ViewPager2 position like vpPisition = wordViewPager.getCurrentItem(); in onStop function.
vpPisition is a global variable.
as #Daniel Kim but a java version
RecyclerView rvOfViewPager2 = (RecyclerView) viewPager2.getChildAt(0);
rvOfViewPager2.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
rvOfViewPager2.getViewTreeObserver().removeOnGlobalLayoutListener(this);
viewPager2.setCurrentItem(currentTabId, false);
}
});
First You need to Initilaze the Main activity under any listener or button You want then After that You need to put this Line..
here MainActvity is the Viewpager Main Class You are using and and 2 is the position where you want to move
MainActivity main = (MainActivity ) mContext;
main.selectTab(2, true);
I have been looking for this answer a while, and i haven't found any good solution which would help me getting started in creating this. This is what i would like to do. Like we have view types in lists and we can show different layouts on different position in lists using those view types, i would like to do that also with viewpager. I'm showing some images from server in viewpager, so user can swipe them, but i would like to show user between those images on every 5 image ad. How can i accomplish that?
This is how my viewpager adapter looks:
private class JokesImagesAdapter extends FragmentPagerAdapter {
public JokesImagesAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
JokePageFragment fragment = new JokePageFragment();
fragment.setArguments(jokes.get(position).toBundle());
return fragment;
}
#Override
public int getCount() {
return jokes.size();
}
}
And i guess that probably i need to create one more fragment and call it here with implementation of ads.
What kind of ads you want to show in your app - Interstitial or Native ad?
If you want to just show an interstitial ad on every 5 swipes - just attach an OnPageChangeListener to your ViewPager and count the swipes.
If you want to show a native ad, you have to create a new fragment (as you thought) which will be showing the ad. You have to count and return the ad fragment in the getItem() method of your adapter. Another way to handle this is to use one fragment which will be notified whether to show or not an ad view or a normal view.
What I believe is that you should modify your jokes model a little, which could accept objects instead of just images(and your custom parameters) and then cast the object to the required datatype and then while populating jokes, you should add the ad object every 5th position, that would do the work.
After reading up hordes of SO answers, this challenge remains.
This is the relevant piece of code in a v4 FragmentStatePagerAdapter:
#Override
public int getCount()
{
int count = 2;
if (pref_dealsOnly)
count = 1;
return count;
}
Like you already guessed, it just crashes with the following exception:
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 2, found: 1 Pager id: com.droid.shopper:id/shopperMainPager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class com.sndroid.globeshopper.shopper.ShopperJournal$JournalPagerAdapter
I fail to understand why the exception occurs.
Please help on how to accomplish what seems to be so simple and apparent - to return a getCount() value in a v4 FragmentStatePagerAdapter dynamically. Kindly let me know if more code is required.
Thanks in advance!
getCount() may be called several times by the ViewPager. It must remain constant, for the life of that PagerAdapter, for reliable results with FragmentPagerAdapter and FragmentStatePagerAdapter.
In theory, you could do what the error message tells you and call notifyDataSetChanged() on the PagerAdapter at the point when getCount() will start returning a different value. While that can work with a custom PagerAdapter implementation, neither FragmentPagerAdapter nor FragmentStatePagerAdapter used to handle it all that well. I wound up creating another PagerAdapter implementation to support adding and removing pages. It is possible that FragmentPagerAdapter and/or FragmentStatePagerAdapter are behaving better nowadays, though I doubt it.
In your case, it may be a matter of swapping in a different PagerAdapter at the point when pref_dealsOnly changes value.
I am currently using a ViewPager object to create a gallery of dynamically loaded photos (from a remote server). I noticed that a ViewPager object relies heavily on knowing the number of pages (or pictures in my case) in advance, while in my situation I don't know.
Am I right? And if I am, is there an alternative that will make sliding between pictures very easy (that's what I like about ViewPager)?
Thanks in advance
Am I right?
Well, you need to have a getCount() method on your PagerAdapter that returns something. If you wish to define that as "relies heavily", then, use, it "relies heavily".
And if I am, is there an alternative that will make sliding between pictures very easy (that's what I like about ViewPager)?
Use ViewPager.
While your images may be loaded dynamically, probably the count of images is knowable in advance. In that case, retrieve that value, then use that for getCount().
Otherwise, have getCount() return 1000000 or something similarly huge. If you find you reach the end of your available pictures, call notifyDataSetChanged() and have your PagerAdapter return the right value from getCount() (since you know it now). Or, have the remaining pages show some placeholder.
For Infinite Scrolling, I figured out one solution to it.
Here's how I am doing it:
No looping is required in this case. No matter what your getCount() is.
After setting the pager adapter, I am setting a setOnPageChangeListener to the view pager like this:
myPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//Define the focused page before your onCreate()..private int focusedPage = 0;
focusedPage = position;
}
//We don't have to do anything here.
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
//Here's where the magic is. After you reach the end of the page, you can scroll again and it will move your view to position you desire to put. In my case it's 0.
#Override
public void onPageScrollStateChanged(int arg0) {
myPager.setCurrentItem(0,false);
}
});
I know it's too late to answer this question but this was the solution I found out. Maybe helpful for other users.
It's working perfect for me...Any suggestions to make this answer better will really help me too.
I have got a ViewPager which is populated by a FragmentPagerAdapter. I want to change from the first adapter two another. The problem is that all pages which were loaded before (while having the first adapter) are still the old ones.
I looked at the source code of FragmentPagerAdapter and guess the problem occurs because of the instatiateItem() implementation. Using the tag, which has position and conatiner id in it, the method checks if there is already a Fragment at the position. When there is a Fragment with this tag it is attached. The container id and position do not change when setting a new adapter so it finds the old Fragments.
Do you know a way to remove all old fragments?
I realized that the Fragment tag uses an id, obtained by getItemId() and not the position. To solve my issue I have overwritten getItemId() and use totally different ids in the different FragmentPagerAdapters.
#Override
public long getItemId(int position) {
return mPagerId*100+position;
}
mPagerId is an unique integer that is assigned in the constructor. If you have more than 100 pages you should replace 100 with 1000.