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

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

  • 相关阅读:
    轻轻松松看懂Spring AOP源码
    centos7安装openjdk8
    使用fiddler做弱网测试
    测试术语-好东西要跟大家一块分享-2
    测试思想-好东西与大家分享-1
    session、token、cookie的区别
    接口测试和功能测试的区别
    常见bug解析-移动端
    接口测试的简介
    软件测试基本理论
  • 原文地址:https://www.cnblogs.com/deman/p/4259971.html
Copyright © 2011-2022 走看看