主要活动
package example.antonio.activitydemo;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.support.v4.app.*;

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final FragmentManager fragmentManager = getSupportFragmentManager();

        Button button = (Button) findViewById(R.id.button);
        button.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirstFragment fragment = new FirstFragment();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                fragmentTransaction.add(R.id.container,fragment);
                fragmentTransaction.commit();
            }
        });

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SecondFragment fragment = new SecondFragment();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                fragmentTransaction.replace(R.id.container,fragment);
                fragmentTransaction.commit();
            }
        });
    }
}

FirstFragment

package example.antonio.activitydemo;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;

public class FirstFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInsanceState) {
        return inflater.inflate(R.layout.first_fragment,container,false);
    }
}

SecondFragment

package example.antonio.activitydemo;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;

public class SecondFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,Bundle savedInsanceState) {
        return inflater.inflate(R.layout.second_fragment,false);
    }
}

他们的XML文件:

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start1"
        android:id="@+id/button"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start2"
        android:id="@+id/button2"/>

</LinearLayout>

first_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#000000">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First!"
        android:textColor="#ffffff"/>


</FrameLayout>

second_fragment.xml就像前一个一样,只有android:text =“Second!”

这是奇怪的事情,当我点击4次Start1按钮然后我得到4倍的单词First!,直到这里一切正常.如果我单击Start2按钮,我会期望删除前面的4个片段并添加一个新的片段,其外观为Second!.这是我从文档中理解的:

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.

但这是我得到的:

After I click 4 times <code></p>Start1</code> button


After I click <code></p>Start2</code> button

我试着阅读源代码,也许我发现了什么是“问题”,我想知道你的想法,如果是我,我在某个地方犯了错误.

以下是BackStackRecord.java的片段,run()方法:

case OP_REPLACE: {
                    Fragment f = op.fragment;
                    int containerId = f.mContainerId;
                    if (mManager.mAdded != null) {
                        for (int i = 0; i < mManager.mAdded.size(); i++) {
                            Fragment old = mManager.mAdded.get(i);
                            if (FragmentManagerImpl.DEBUG) {
                                Log.v(TAG,"OP_REPLACE: adding=" + f + " old=" + old);
                            }
                            if (old.mContainerId == containerId) {
                                if (old == f) {
                                    op.fragment = f = null;
                                } else {
                                    if (op.removed == null) {
                                        op.removed = new ArrayList<Fragment>();
                                    }
                                    op.removed.add(old);
                                    old.mNextAnim = op.exitAnim;
                                    if (mAddToBackStack) {
                                        old.mBackStacknesting += 1;
                                        if (FragmentManagerImpl.DEBUG) {
                                            Log.v(TAG,"Bump nesting of "
                                                    + old + " to " + old.mBackStacknesting);
                                        }
                                    }
                                    mManager.removeFragment(old,mTransition,mTransitionStyle);
                                }
                            }
                        }
                    }

这是FragmentManager.java的片段:

public void removeFragment(Fragment fragment,int transition,int transitionStyle) {
        if (DEBUG) Log.v(TAG,"remove: " + fragment + " nesting=" + fragment.mBackStacknesting);
        final boolean inactive = !fragment.isInBackStack();
        if (!fragment.mDetached || inactive) {
            if (false) {
                // Would be nice to catch a bad remove here,but we need
                // time to test this to make sure we aren't crashes cases
                // where it is not a problem.
                if (!mAdded.contains(fragment)) {
                    throw new IllegalStateException("Fragment not added: " + fragment);
                }
            }
            **if (mAdded != null) {
                mAdded.remove(fragment);
            }**
            if (fragment.mHasMenu && fragment.mMenuVisible) {
                mNeedMenuInvalidate = true;
            }
            fragment.mAdded = false;
            fragment.mRemoving = true;
            movetoState(fragment,inactive ? Fragment.INITIALIZING : Fragment.CREATED,transition,transitionStyle,false);
        }
    }

正如您所看到的,removeFragment方法从mAdded中删除了一个frament,但是在run()方法之后,i索引没有被修改,它从它离开的地方重新启动,这样就会丢失一些元素……

解决方法

使用linearlayout作为容器无法实现此方案.

如果您尝试将此片段用作linearlayout中的容器,则可以实现此目的.请参阅此链接以获得进一步说明

Android – fragment .replace() doesn’t replace content – puts it on top

否则使用以下代码进行按钮单击操作,

Button button = (Button) findViewById(R.id.button);
    button.setonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirstFragment fragment = new FirstFragment();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

            fragmentTransaction.add(R.id.container,fragment).addToBackStack(null);
            fragmentTransaction.commit();
        }
    });

    Button button2 = (Button) findViewById(R.id.button2);
    button2.setonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SecondFragment fragment = new SecondFragment();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            for(int i=0; i < getSupportFragmentManager().getBackStackEntryCount(); i++)
                getSupportFragmentManager().popBackStack();
            fragmentTransaction.replace(R.id.container,fragment);
            fragmentTransaction.commit();
        }
    });

希望这会对你有所帮助..谢谢

java – replace()无法与多片段一起正常工作的更多相关文章

  1. HTML5 input新增type属性color颜色拾取器的实例代码

    type 属性规定 input 元素的类型。本文较详细的给大家介绍了HTML5 input新增type属性color颜色拾取器的实例代码,感兴趣的朋友跟随脚本之家小编一起看看吧

  2. amazeui模态框弹出后立马消失并刷新页面

    这篇文章主要介绍了amazeui模态框弹出后立马消失并刷新页面,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  3. 移动HTML5前端框架—MUI的使用

    这篇文章主要介绍了移动HTML5前端框架—MUI的使用的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  4. AmazeUI 模态窗口的实现代码

    这篇文章主要介绍了AmazeUI 模态窗口的实现代码,代码简单易懂,非常不错,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. ios – UIPopoverController出现在错误的位置

    所以我花了一些时间寻找答案,但到目前为止还没有找到任何答案.我正在尝试从UIInputAccessoryView上的按钮呈现弹出窗口.UIBarButtonItem我想显示popover来自定制视图,所以我可以使用图像.我创建这样的按钮:当需要显示popover时,我这样做:但我得到的是:弹出窗口看起来很好,但它应该出现在第一个按钮上时出现在第二个按钮上.然后我发现了这个问题:UIBarButto

  6. ios – 关闭UIBarButtonItem上的突出显示

    我正在尝试使用UIBarButtonItem在我的UIToolbar上添加标题.我使用简单的风格,看起来很好,但我似乎无法让它停止突出显示触摸.“突出显示时触摸”选项不适用于条形按钮项目.有没有快速简便的方法来做到这一点?

  7. 以编程方式调整iOS中的按钮大小

    我正在使用XCode4.6.1并开发iOS6.我在故事板上添加了一个按钮.我在我的实现文件ViewController.m中创建了一个插座:我尝试按如下所示更改按钮b1的属性(在同一个文件中:ViewController.m):当我在模拟器中运行应用程序时,按钮的alpha成功设置为0.5.但是,按钮的位置和大小不会改变.我尝试了各种方法来实现它.然而似乎没有任何作用.我想知道我做错了什么.我对O

  8. 如何在iOS / Swift的顶部导航栏中添加“继续”按钮

    我想在导航栏的右侧添加一个“继续”按钮.如何实现这一目标?我一直在尝试使用UIBarButtonItem上的一些方法,但无法使其正常工作.我迄今为止的最大努力是:但我在第一行遇到错误.它不喜欢“style”参数.我也试过了但没有运气.仍然停留在样式参数上.有任何想法吗?

  9. ios – 将图像添加到界面构建器中的按钮

    我想在我的按钮而不是文本中添加图像.我可以在界面构建器中这样做吗?我可以看一下这个例子吗?

  10. ios – 自定义BackBarButtonItem

    主要原因是您丢失了标准后退按钮滑动动画以更改视图.此外,这意味着我不需要使用自定义按钮或编写自定义方法返回.它只是起作用.希望这也能解决别人的问题,我知道我已经坚持了3个小时!

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部