博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
FragmentTransaction add 和 replace 区别 转
阅读量:4507 次
发布时间:2019-06-08

本文共 1250 字,大约阅读时间需要 4 分钟。

使用 FragmentTransaction 的时候,它提供了这样两个方法,一个 add , 一个 replace .

add 和 replace 影响的只是界面,而控制回退的,是事务。

public abstract FragmentTransaction add (int containerViewId, Fragment fragment, String tag)

Add a fragment to the activity state. This fragment may optionally also have its view (if Fragment.onCreateView returns non-null) into a container view of the activity.

add 是把一个fragment添加到一个容器 container 里。

public abstract FragmentTransaction replace (int containerViewId, Fragment fragment, String tag)

Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

replace 是先remove掉相同id的所有fragment,然后在add当前的这个fragment。

在大部分情况下,这两个的表现基本相同。因为,一般,咱们会使用一个FrameLayout来当容器,而每个Fragment被add 或者 replace 到这个FrameLayout的时候,都是显示在最上层的。所以你看到的界面都是一样的。但是, 使用add的情况下,这个FrameLayout其实有2层,多层肯定要比一层的来得浪费,所以还是推荐使用replace。 当然有时候还是需要使用add的。比如要实现轮播图的效果,每个轮播图都是一个独立的Fragment,而他的容器FrameLayout需要add多个Fragment,这样他就可以根据提供的逻辑进行轮播了。

而至于返回键的时候,这个跟事务有关,跟使用add还是replace没有任何关系。

 

add 在添加第一个项目是,会直接替换掉原来的,而replace+addbackstack方式,会导致内容在回退的时候,显示白屏。

 

转载于:https://www.cnblogs.com/deman/p/4259971.html

你可能感兴趣的文章
sqlserver2005版本的mdf文件,还没有log文件,
查看>>
错误“该伙伴事务管理器已经禁止了它对远程/网络事务的支持”解决方案
查看>>
System x 服务器制作ServerGuide U盘安装Windows Server 2008 操作系统 --不格式化盘
查看>>
前端常见跨域解决方案(全)
查看>>
umi---className设置多个样式
查看>>
网页包抓取工具Fiddler工具简单设置
查看>>
周总结报告
查看>>
Selecting Courses POJ - 2239(我是沙雕吧 按时间点建边 || 匹配水题)
查看>>
Win+R指令(2)
查看>>
codeforces 578c - weekness and poorness - 三分
查看>>
数值微分方程
查看>>
动态规划--电路布线(circuit layout)
查看>>
<转>OD常用断点列表
查看>>
描边时消除锯齿SetSmoothingMode
查看>>
15回文相关问题
查看>>
将VS2013项目转成VS2010项目的方法
查看>>
[置顶] 怎么对待重复的代码
查看>>
多种方法实现H5网页图片动画效果;
查看>>
Ubuntu/CentOS下使用脚本自动安装 Docker
查看>>
源码解读Mybatis List列表In查询实现的注意事项
查看>>