Anonymous Anonymous - 18 days ago 7
Android Question

Android - ViewPager Adapter, set primary item before adapter is instantiated

I know i can do

viewPager.setCurrentItem(position)


to set my view pager at the desired position. My question is if and how i can do this before the adapter is instantiated.

Meaning that if I do

pagerAdapter = new ViewPagerAdapter(arg1,arg2....);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(position);


item 0 is first build and after that the item at the desired position is also build. Which takes double the time...In my adapter each item to be build is quite a lot of work so it would be best to avoid the 0 position item to be build if possible. Maybe by passing the desired position as an argument at the adapter's instantiation...?

Any way to do that?

Answer

You can fool the viewpager to start at a given position before the adapter is set, by calling onRestoreInstanceState, like this:

int currentItem = 5;

Parcel parcel = Parcel.obtain();
writeParcelable(BaseSavedState.EMPTY_STATE, 0);

writeInt(currentItem);
writeParcelable(null, 0);

setDataPosition(0);
SavedState savedState = ViewPager.SavedState.CREATOR.createFromParcel(parcel);

mPager.onRestoreInstanceState(savedState);

mPager.setAdapter(mAdapter);
Comments