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

▼魔方 西西 提交于 2019-12-03 01:41:00

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);

If the time and work is what you're worry about, I'd try to avoid building the page at position 0 until the desired one has been built. You could use a variable lets say "desiredPageHasBeenBuilt" in your adapter, when requesting the item at position 0 you could return an "empty page" if the variable desiredPageHasBeenBuilt is false, when your desired page has been build set the variable to true and the page 0 can be built.

You can just set blank adapter and after that set your real adapter this way you will "trick" the viewpager and you want load any data you dont want to.

this.viewPager.setAdapter(new PagerAdapter() {
        @Override
        public int getCount() {
            return 0;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return false;
        }
    });
this.viewPager.setCurrentItem(imagePosition, false);
this.viewPager.setAdapter(adapter);
this.viewPager.setCurrentItem(imagePosition, false);

For a solution that works in Android M as well as older versions, use reflection as follows:

int currentItem = 5;

// Set initial position first...
Field field = ViewPager.class.getDeclaredField("mRestoredCurItem");
field.setAccessible(true);
field.set(mPager, currentItem);

// ...and then set adapter
mPager.setAdapter(adapter);

Using reflection is safe, because you control the ViewPager implementation (it's included with your app).

If you use Proguard, then you need to include the following in its config:

-keepclassmembers class android.support.v4.view.ViewPager {
    private int mRestoredCurItem;
}  

or the field mRestoredCurItem will be renamed by Proguard.

Maybe this is not the answer you're looking for, but have you tried to it as it was designed? Do not start heavy work on page fragment before it is attached to the screen. That way you'll get that behavior you want without hacking android implementation.

you can do this trick:

refactor all of your heavy work into a function, because creating a fragment is not takes much time, and only execute the function when user is going to see it by calling that function inside OnPageChangeListener listener and at the

@Override
public void onPageSelected(int position){
    // call your function that do heavy working  
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!