讓多個Fragment 切換時不重新實例化、FragmentTabHost切換Fragment時避免UI重新加載


http://www.tuicool.com/articles/FJ7VBb

FragmentTabHost切換Fragment時避免UI重新加載


不過,初次實現時發現有個缺陷,每次FragmentTabHost切換fragment時會調用onCreateView()重繪UI。

解決方法,在fragment onCreateView 里緩存View:

Java代碼 收藏代碼
private View rootView;// 緩存Fragment view

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
Log.i(TAG, "onCreateView");

if (rootView == null)
{
rootView = inflater.inflate(R.layout.fragment_1, null);
}
// 緩存的rootView需要判斷是否已經被加過parent,如果有parent需要從parent刪除,要不然會發生這個rootview已經有parent的錯誤。
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
{
parent.removeView(rootView);
}
return rootView;
}

 

 

http://www.yrom.net/blog/2013/03/10/fragment-switch-not-restart/

在項目中需要進行Fragment的切換,一直都是用replace()方法來替換Fragment:

1
2 3 4 5 6 7 8 9 
 public void switchContent(Fragment fragment) {  if(mContent != fragment) {  mContent = fragment;  mFragmentMan.beginTransaction()  .setCustomAnimations(android.R.anim.fade_in, R.anim.slide_out)  .replace(R.id.content_frame, fragment) // 替換Fragment,實現切換  .commit();  }  } 

但是,這樣會有一個問題:
每次切換的時候,Fragment都會重新實例化,重新加載一邊數據,這樣非常消耗性能和用戶的數據流量。

就想,如何讓多個Fragment彼此切換時不重新實例化?

翻看了Android官方Doc,和一些組件的源代碼,發現,replace()這個方法只是在上一個Fragment不再需要時采用的簡便方法。

正確的切換方式是add(),切換時hide(),add()另一個Fragment;再次切換時,只需hide()當前,show()另一個。
這樣就能做到多個Fragment切換不重新實例化:

1
2 3 4 5 6 7 8 9 10 11 12 
 public void switchContent(Fragment from, Fragment to) {  if (mContent != to) {  mContent = to;  FragmentTransaction transaction = mFragmentMan.beginTransaction().setCustomAnimations(  android.R.anim.fade_in, R.anim.slide_out);  if (!to.isAdded()) { // 先判斷是否被add過  transaction.hide(from).add(R.id.content_frame, to).commit(); // 隱藏當前的fragment,add下一個到Activity中  } else {  transaction.hide(from).show(to).commit(); // 隱藏當前的fragment,顯示下一個  }  }  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM