Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ViewPager 切換 Fragment 時避免 onCreateView 頻繁調用的優化

編輯:關於 Android 開發

ViewPager 切換 Fragment 時避免 onCreateView 頻繁調用的優化


使用 ViewPager 切換 Fragment 時,我最初採用系統自帶的 FragmentPagerAdapter,結果發現每次切換都會頻繁調用 onCreateView()。

翻閱 FragmentPagerAdapter 源碼後,發現兩個關鍵之處:在 instantiateItem 中,對於已存在的 Fragment 使用了 attach;而在 destroyItem 中,則使用了 detach。正是這對 attach/detach 的頻繁使用,導致了 onCreateView 被反覆觸發。

@Override public Object instantiateItem(ViewGroup container, int position) { if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } final long itemId = getItemId(position); String name = makeFragmentName(container.getId(), itemId); Fragment fragment = mFragmentManager.findFragmentByTag(name); if (fragment != null) { //該處使用attach導致頻繁調用oncreatview mCurTransaction.attach(fragment); } else { fragment = getItem(position); mCurTransaction.add(container.getId(), fragment, makeFragmentName(container.getId(), itemId)); } if (fragment != mCurrentPrimaryItem) { fragment.setMenuVisibility(false); fragment.setUserVisibleHint(false); } return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } //該處使用detach導致頻繁調用oncreatview mCurTransaction.detach((Fragment)object); }

找到「元兇」後就好辦了。思路很簡單:自定義一個適配器,把 attach 改為 show、把 detach 改為 hide,即可完美解決問題。

@Override public Object instantiateItem(ViewGroup container, int position) { if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } final long itemId = getItemId(position); String name = makeFragmentName(container.getId(), itemId); Fragment fragment = mFragmentManager.findFragmentByTag(name); if (fragment != null) { //用show而不用attach,防止頻繁調用oncreatview mCurTransaction.show(fragment); } else { fragment = getItem(position); mCurTransaction.add(container.getId(), fragment, makeFragmentName(container.getId(), itemId)); } if (fragment != mCurrentPrimaryItem) { fragment.setMenuVisibility(false); fragment.setUserVisibleHint(false); } return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } //用hide而不用detach,防止頻繁調用oncreatview mCurTransaction.hide((Fragment) object); }

 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved