[Android]Fragment加载替换add,show,hide,replace方法
来源:互联网 发布:java redis视频教程 编辑:程序博客网 时间:2024/03/28 23:54
本文主要探讨Fragment切换的细节问题。Demo连接已给出。
关于Fragment的基础知识可以移步:
http://developer.android.com/guide/components/fragments.html
针对在一个Activity中的某个Layout中切换Fragment,,无非两种方法:
1)使用replace方法把原有的Fragment替换掉;
2)使用hide和show方法,把已经添加过的Fragment再次显示出来。
两个方法之间的区别。
1)replace方法,在某Layout中已经有Fragment A存在,现在需要把Fragment B替换(显示出来)。
使用replace(R.id.layout,B)即可以。但是这带来一个问题,原来A会在被replace后被销毁,会调用其生命周期函数(onDestoryView(),onPause(),onDestory())。
如果频繁地replace Fragment会不断创建新实例,销毁旧的,无法重用。
多次切换,会导致Fragment上的View无法加载的问题(onCreateView方法不再调用,原因是replace后没有再次新建Fragment实例)。
总结:如果旧Fragment无须再次使用,可以使用replace方法将其销毁。
如图所示,日志显示Fragment A 被创建
下面将A replace替换成B,A被销毁,而B被创建
再次从B replace替换成A
可以看见,B也是被销毁,而Fragment A再次被创建。
2)hide和show
<span style="font-size:14px;"><span style="white-space: pre;"></span>/** * 使用hide和show方法切换Fragment * * @param fragment 需要切换的fragment */private void switchFragment(Fragment fragment) {if (fragment != mTempFragment) {if (!fragment.isAdded()) {getFragmentManager().beginTransaction().hide(mTempFragment).add(R.id.container, fragment).commit();} else {getFragmentManager().beginTransaction().hide(mTempFragment).show(fragment).commit();}mTempFragment = fragment;}}</span>
简单来说,这种方式就是要填补方法(1)中的不足:不断重用Fragment的情况。
如图所示,Fragment A新建
切换到Fragment B
再次切换到A,没有调用生命周期函数
再次切换到B,没有调用生命周期函数
总结:如果Fragment需要重用或者不断切换,可以使用该方法。
注意:该方法会有个特殊的“问题”,只会给予子控件所需要的宽高而不是使用layout的宽高(即使是fill_parent或match_parent)。解决方法是在layout下再嵌套一个宽高都适合的字layout。
以上。
demo下载地址:
https://github.com/ChenSiLiang/CSDN.git
- [Android]Fragment加载替换add,show,hide,replace方法
- Fragment加载替换add,show,hide,replace方法
- Fragment加载替换add,show,hide,replace方法
- Fragment加载替换add,show,hide,replace方法
- Fragment加载轮换add,show,hide,replace方法
- Fragment生命周期及add、replace、remove、hide&show方法分析
- android Fragment FragmentActivity 选项卡 replace add hide show
- Fragment add、show、hide、replace、remove、
- Fragment show hide,replace
- Android Fragment 真正的完全解析(上) add remove replace detach attach hide show
- Android Fragment 真正的完全解析(上) add remove replace detach attach hide show
- FragmentTransition replace add show hide方法的使用和差异
- android碎片的replace()和add()、hide()、show()的区别
- Fragment add hide show方式
- Fragment切换 保存状态(add show hide)
- Fragment的show,add,hide使用
- FragmentTransaction的add(),hide(),show()方法与Replace()方法的比较
- 安卓中用show()和hide()方法来代替转跳fragment的replace()方法
- touch事件的分发和消费机制
- Solr4.10.3中整合中文分词mmseg4j-1.9.1
- 阿里云 安装docker
- 蓝桥杯 基础练习 十六进制转八进制
- 3秒钟解决“/”应用程序中的服务器错误
- [Android]Fragment加载替换add,show,hide,replace方法
- 实习篇---千里难寻的是朋友
- 2015年1月25号到31号日志
- 锚点的简单使用
- java复制文件FileInputStream BufferedFileInputStream Paths Files
- 基础练习 查找整数
- The specified JTAG device (in the Target Connection tab) is invalid.
- 04-3. 统计素数并求和(20)
- LINUX netlink机制