Lee Jeongmin
Lee Jeongmin

Reputation: 893

Android Set viewpager's first item

I have a viewpager. This viewpager can have dynamic number of pages depends on server and user can start with any page they want. So I programmed like below..

mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(mStartPosition);

mStartPosition is a position to start..

My question is here. This view pager always load pages where 0, 1 and mStartPosition and nearby pages loaded sequentially. If mStartPosition is 10, then loading 0, 1, and load 9,10,11. It slow down performance and waste data.

I want just start with mStartPosition and nearby page. Help me~!

Upvotes: 4

Views: 3291

Answers (2)

Phil
Phil

Reputation: 1200

It's Android limitation so 0,1, 10,9,11 is expected if you are setting the adapter after the pager has been layout-ed. Otherwise you will get 10, 9, 11

Long answer: Check the source code. In the source code (at least in support-v4-23.4.0) when populating the pager with an adapter mViewPager.setAdapter(mAdapter); the pager will always go to position 0 because it's member mCurItem is 0. And on the next line when you call mViewPager.setCurrentItem(mStartPosition, false); it will change the mCurItem. If you try to call mViewPager.setCurrentItem(mStartPosition, false); before mViewPager.setAdapter(mAdapter); in order to set mCurItem it won't work again as the adapter in still null and won't work as it will return before setting. But if you set the adapter before layouting the pager, a specific property in it mFirstLayout won't cause population right away and by the time it does the mCurItem will be set.

So basically: Use those calls before you are layouting the pager.

Upvotes: 2

Sohaib
Sohaib

Reputation: 11297

setCurrentItem(int item) sets current item with smooth animated transition.

You just need to use mViewPager.setCurrentItem(mStartPosition, false);

Then it will only load 9,10,11

Upvotes: 3

Related Questions