让多个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