片段导航(BackStack)

时间:2014-05-27 15:08:39

标签: android android-fragments back-stack android-navigation

我的应用程序有一个活动,其中包含多个片段的布局(FrameLayout)。

  • 在应用程序的开头,它会显示一个位置列表( PlacesFragment )。
  • 单击一个地点时,会添加一个显示凸轮列表( CamFragment )的片段。在这个片段里面还有一个按钮“info”。
  • 当用户按下“信息”按钮时,会添加一个显示该地点信息的新片段( InfoPlaceFragment )。

以下是图解说明: enter image description here

我希望能够从“InfoPlaceFragment(C)”返回“CamFragment(B)”,并从“CamFragment(B)”返回“PlacesFragment(A)”。

  • 一个问题
    1)是否有可能实现这一点或替代解决方案更好?

-------编辑-------

解决方案

“MainActivity.java”

onPlaceParse() //收到服务器的数据时会调用此方法:

  // Here I create the "PlaceFragment"
  fManager = getSupportFragmentManager();
  fragmentPlaces = new PlacesFragment();

  fManager.beginTransaction()
     .replace(R.id.fragment_list_container, fragmentPlaces)
     .commit();

onResortSelected //选择度假村时会调用此方法

   fragmentCams = new CamsFragment();

   fManager.beginTransaction()
    .replace(R.id.fragment_list_container, fragmentCams)
    .addToBackStack(null)
    .commit();

onButtonInfoSelected //选择btn信息时调用此方法

    fragmentInfo = new InfoResortFragment();

    fManager = getSupportFragmentManager();
    fManager.beginTransaction()
        .replace(R.id.fragment_list_container, fragmentInfo, "Info")
                    .addToBackStack(null)
        .commit();

当您按下后退按钮时,如果您在“信息片段”中,它将返回到“PlaceFragment”,如果您在“CamsFragment”中,它将返回“PlacesFragment”。

2 个答案:

答案 0 :(得分:2)

这是可能的,您需要在片段事务中调用addToBackStack(null)

参考:Providing Proper Back Navigation

答案 1 :(得分:1)

当您创建将添加/删除/替换(或您使用的任何模式)片段的FragmentTransaction时,请务必致电addToBackStack()。然后,当用户按下后退按钮时,系统将自动循环返回添加到后堆栈的条目,其顺序与它们最初添加的方式相反。您无需额外的工作! :)

相关问题