我们需要解决这个问题:切换时,可以实现单独的消息到左和右,但我不知道的情况下根据岗位总数。只是不知道ViewPagerAdapter的getCount数量。
因为帖子内容的数据图片和布局比較复杂。所以不让ViewPager缓存。否则消耗内存太大。
重写ViewPager
public class LazyViewPager extends ViewGroup { private boolean isCanScroll = true; public boolean isCanScroll() { return isCanScroll; } public void setCanScroll(boolean isCanScroll) { this.isCanScroll = isCanScroll; } private static final String TAG = "LazyViewPager"; private static final boolean DEBUG = false; private static final boolean USE_CACHE = false; <span style="color:#ff0000;">private static final int DEFAULT_OFFSCREEN_PAGES = 0;//默认的载入页面,ViewPager是1个,所以会载入两个Fragment</span> private static final int MAX_SETTLE_DURATION = 600; // ms
public void setAdapter(PagerAdapter adapter,int position) { if (mAdapter != null) { mAdapter.unregisterDataSetObserver(mObserver); mAdapter.startUpdate(this); for (int i = 0; i < mItems.size(); i++) { final ItemInfo ii = mItems.get(i); mAdapter.destroyItem(this, ii.position, ii.object); } mAdapter.finishUpdate(this); mItems.clear(); removeAllViews(); mCurItem = 0; scrollTo(0, 0); } mAdapter = adapter; if (mAdapter != null) { if (mObserver == null) { mObserver = new PagerObserver(); } mAdapter.registerDataSetObserver(mObserver); mPopulatePending = false; if (mRestoredCurItem >= 0) { mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader); <span style="color:#ff0000;"> if(position>0){ setCurrentItemInternal(position, false, true); }else{ setCurrentItemInternal(mRestoredCurItem, false, true); }</span> mRestoredCurItem = -1; mRestoredAdapterState = null; mRestoredClassLoader = null; } else { populate(position); } } }
只是前提是设置这个ViewPager的Adapter的getCount的数量为1000或者Integer.Max
假设要实现ViewPager的Fragment不反复运行onCreateView方法,须要重写destroyItem
private class MyFragmentAdapter extends FragmentPagerAdapter{ public MyFragmentAdapter(FragmentManager fm) { super(fm); // TODO Auto-generated constructor stub } @Override public Fragment getItem(int arg0) { // TODO Auto-generated method stub MyFragment fragment = new MyFragment(arg0); return fragment; } @Override public int getCount() { // TODO Auto-generated method stub return 10; } @Override public void destroyItem(ViewGroup container, int position, Object object) { // TODO Auto-generated method stub // super.destroyItem(container, position, object); } @Override public void destroyItem(View container, int position, Object object) { // TODO Auto-generated method stub // super.destroyItem(container, position, object); } }
假设要设置ViewPager实现左右无限切换,能够通过重写Adapter的getItem()方法。
@Override public Fragment getItem(int arg0) { // TODO Auto-generated method stub MyFragment fragment = fragments.get(arg0%4); return fragment; }
前提是getCount是个非常大的数
版权声明:本文博主原创文章,博客,未经同意不得转载。