Android-ViewPager适配器,在实例化适配器之前设置主要项目 [英] Android - ViewPager Adapter, set primary item before adapter is instantiated
问题描述
我知道我能做到
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.
意思是,如果我这样做
pagerAdapter = new ViewPagerAdapter(arg1,arg2....);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(position);
首先构建项目0,然后再构建所需位置的项目.这花费了两倍的时间...在我的适配器中,每个项目都需要大量的工作来构建,因此,如果可能的话,最好避免构建0位置的项目.也许是通过在适配器的实例化处将所需位置作为参数传递的??
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 needs quite a lot of work to be build, 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...?
有什么办法吗?
推荐答案
您可以通过调用onRestoreInstanceState来欺骗viewpager在设置适配器之前从给定位置开始,如下所示:
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);
这篇关于Android-ViewPager适配器,在实例化适配器之前设置主要项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!