在Android中的BackStack中添加片段

时间:2017-06-20 08:16:31

标签: android android-fragments

我有两个片段正在取代另一个片段。我需要当用户点击后退按钮时它转到上一个片段。第一个片段从Activity添加,第二个片段替换Fragment

内的第一个片段

以下是我帮助您理解的代码。

活动

 // inside onCreate() method

Fragment camInitializer = new Initializer();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.cameraLayout, camInitializer, "camInitializer");
    fragmentTransaction.addToBackStack("camInitializer");
    fragmentTransaction.commit();

Cam Initializer Fragment

 // inside onClick() method
Fragment cameraEditing = new Editing();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.cameraLayout, cameraEditing,"cameraEditing");
    fragmentTransaction.commit();

cameraEditing片段当我第一次点击后退按钮时,没有任何事情发生,然后第二次再次点击后退按钮应用程序像往常一样处于暂停状态。但我希望当用户第一次点击后退按钮时,它会将cameraEditing片段替换为camInitializer

2 个答案:

答案 0 :(得分:5)

使用类似的东西。

<强>活动

Fragment camInitializer = new Initializer();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.cameraLayout, camInitializer, "camInitializer");
    //fragmentTransaction.addToBackStack("camInitializer");
    fragmentTransaction.commit();

<强>片段

Fragment cameraEditing = new Editing();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.cameraLayout, cameraEditing,"cameraEditing");
    fragmentTransaction.addToBackStack("cameraEditing");
    fragmentTransaction.commit();

这对我来说很好

答案 1 :(得分:0)

在您的活动中,请尝试以下代码

@Override
public void onBackPressed() 
{
  if(getFragmentManager().getBackStackEntryCount() > 0)
    getFragmentManager().popBackStack();
  else
   super.onBackPressed();
}

参考:

Resuming a previous fragment onBackPressed()?