多个Fragment 切换时不重新实例化
2014-04-14 14:34
375 查看
在项目中需要进行Fragment的切换,一直都是用replace()方法来替换Fragment:
[java] view
plaincopy
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切换不重新实例化:
[java] view
plaincopy
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,显示下一个
}
}
[java] view
plaincopy
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切换不重新实例化:
[java] view
plaincopy
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,显示下一个
}
}
相关文章推荐
- Cocos2d-x 2.2.3 + Visual studio 2013 + python2.7.5开发环境搭建
- 深圳公司注册新政策 无须地址0资金一样注册深圳公司
- 简单选择排序的体会
- 大众化PDF转Word工具
- 打印1到最大的n位数
- 三层架构和SQL语言
- IOS 使用Xcode5制作静态库详解
- JSP或servlet中(以及上传下载文件)中文乱码或不显示的解决方案
- 37条Java面向对象设计的经验原则,成为高级程序员必备
- Android make: *** No rule to make target
- Exadata V2数据库一体机的几大致命缺点
- 美国时代周刊关于心脏流血漏洞的报道
- 友元解决了那些问题
- Median of Two Sorted Arrays
- iOS-Label中字符显示
- 手把手教你uiautomator_android自动化测试第一个示例
- win7 64位 VC 2010下配置OpenCV2.4.4
- nginx跨域
- Python 用hashlib求中文字符串的MD5值
- Ubuntu修改环境变量