你的位置:首页 > 软件开发 > 操作系统 > 使用ViewPager切换Fragment时,防止频繁调用OnCreatView

使用ViewPager切换Fragment时,防止频繁调用OnCreatView

发布时间:2016-11-23 19:00:06
使用ViewPager切换Fragment,我原先使用系统自带的适配器FragmentPagerAdapter。切换fragment时,频繁调用oncreatview()。查看FragmentPagerAdapter的源码,发现两个关键的地方 1 @Override 2 pu ...

使用ViewPager切换Fragment,我原先使用系统自带的适配器FragmentPagerAdapter。

切换fragment时,频繁调用oncreatview()。

查看FragmentPagerAdapter的源码,发现两个关键的地方

 1 @Override 2   public Object instantiateItem(ViewGroup container, int position) { 3     if (mCurTransaction == null) { 4       mCurTransaction = mFragmentManager.beginTransaction(); 5     } 6  7     final long itemId = getItemId(position); 8  9     // Do we already have this fragment?10     String name = makeFragmentName(container.getId(), itemId);11     Fragment fragment = mFragmentManager.findFragmentByTag(name);12     if (fragment != null) {13       if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);14      //该处使用attach导致频繁调用oncreatview15       mCurTransaction.attach(fragment);16 17     } else {18       fragment = getItem(position);19       if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);20       mCurTransaction.add(container.getId(), fragment,21           makeFragmentName(container.getId(), itemId));22     }23     if (fragment != mCurrentPrimaryItem) {24       fragment.setMenuVisibility(false);25       fragment.setUserVisibleHint(false);26     }27 28     return fragment;29   }30 31   @Override32   public void destroyItem(ViewGroup container, int position, Object object) {33     if (mCurTransaction == null) {34       mCurTransaction = mFragmentManager.beginTransaction();35     }36     if (DEBUG) Log.v(TAG, "Detaching item #" + getItemId(position) + ": f=" + object37         + " v=" + ((Fragment)object).getView());38     //该处使用detach导致频繁调用oncreatview39     mCurTransaction.detach((Fragment)object);40   }

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:使用ViewPager切换Fragment时,防止频繁调用OnCreatView

关键词:ie

ie
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。