popBackStack()后addToBackStack不起作用 [英] popBackStack() after addToBackStack does not work

查看:579
本文介绍了popBackStack()后addToBackStack不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目包含两个片段:

My project contains two fragment :


  • 碎裂:应用程序启动时默认加载的片段

  • FragmentB:替换碎裂当点击一个按钮完成

  • FragmentA : the fragment loaded by default when the app starts
  • FragmentB : replace the fragmentA when a click on a button is done.

这是我的主视图的XML:

This is the XML of my main view :

<?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">

    <fragment
        android:id="@+id/main_fragment_container"
        android:name="fragmentA"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </fragment>

</LinearLayout>

当我想替换碎裂 FragmentB ,我用这个code:

When I wish to replace the FragmentA by the FragmentB, I use this code :

FragmentTransaction fragmentTransaction = getSupportFragmentManager()
            .beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.main_fragment_container, new FragmentB());
fragmentTransaction.commit();

这code正常工作。我的碎裂被新的 FragmentB 替换。但是,当点击上后退按钮做的,我希望替换 FragmentB 碎裂使用 popBackStackImmediate()

This code works fine. My FragmentA is replaced by the new FragmentB. But when a click is done on the back button, I wish replace the FragmentB by the FragmentA by using popBackStackImmediate().

这是code我使用:

if (getSupportFragmentManager().getBackStackEntryCount() > 0){
    boolean done = getFragmentManager().popBackStackImmediate();
    fragmentTransaction.commit();
}

功能 popBackStackImmediate 返回始终为false和 FragmentB 仍然在前台。

The function popBackStackImmediate return always false and the FragmentB still in foreground.

为什么当我打电话的碎裂不会取代FragmentB popBackStackImmediate ?是任何人有一个想法,以解决我的问题?

Why the FragmentA does not replace the FragmentB when I call popBackStackImmediate ? Is anybody has an idea to solve my problem?

在此先感谢

推荐答案

您使用 getSupportedFragmentManager()来代替碎裂 FragmentB 。但是,你叫 popBackStack() getFragmentManager()

You use the getSupportedFragmentManager() to replace FragmentA by FragmentB. But you call popBackStack() on the getFragmentManager().

如果您要添加的片段到 android.support.v4.app.FragmentManager 你也有叫 popBackStack()在同一个 FragmentManager

If you are adding the Fragments to the android.support.v4.app.FragmentManager you also have to call popBackStack() on the same FragmentManager.

这code应该解决的问题:

This code should solve the problem:

if (getSupportFragmentManager().getBackStackEntryCount() > 0){
    boolean done = getSupportFragmentManager().popBackStackImmediate();
}

这篇关于popBackStack()后addToBackStack不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆