标签:des style blog http io color os ar java
需要解决问题:单个帖子进入时候可以实现左右切换,并且是在不知道帖子总数的情况下,就是不知道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的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); } }
@Override public Fragment getItem(int arg0) { // TODO Auto-generated method stub MyFragment fragment = fragments.get(arg0%4); return fragment; }
标签:des style blog http io color os ar java
原文地址:http://blog.csdn.net/fancylovejava/article/details/40581527