我有两个片段正在取代另一个片段。我需要当用户点击后退按钮时它转到上一个片段。第一个片段从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
答案 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();
}
参考: