zoukankan      html  css  js  c++  java
  • FragmentTransaction add 和 replace 区别

    使用 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没有任何关系。

  • 相关阅读:
    Windows服务的安装及配合定时器编写简单的程序
    关于VS2019使用Git时遇到的Bug
    记一次工作中的小BUG
    .Net WebApi接口Swagger集成简单使用
    kettle 创建数据库资源库
    C# 语法 i++;++i;i--;--i
    MSDN
    Jenkins持续集成(下)-Jenkins部署Asp.Net网站自动发布
    Jenkins持续集成(上)-Windows下安装Jenkins
    自动发布-asp.net自动发布、IIS站点自动发布(集成SLB、配置管理、Jenkins)
  • 原文地址:https://www.cnblogs.com/xingyyy/p/3615793.html
Copyright © 2011-2022 走看看