简体   繁体   English

如何用片段修复后退导航?

[英]How can I fix the back navigation with fragments?

I have a problem implementing the back navigation. 我在实施后退导航时遇到问题。

Activity A1 starts Activity A2 . 活动A1启动活动A2 A2 contains a full screen fragment: A2包含一个全屏片段:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >

    <!-- fragment goes here -->

</RelativeLayout>

in A2 's onCreate() I load the fragment F1 in the container above: A2onCreate()我将片段F1加载到上面的容器中:

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    setContentView(R.layout.activity_main);
    replaceFragment(new AccountHomeFragment());
}

public void replaceFragment(Fragment f){
     FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
     fragmentTransaction.replace(R.id.fragment_container, f);
     fragmentTransaction.addToBackStack(f.getClass().getSimpleName());
     fragmentTransaction.commit();
}

And at some point the user clicks on a button and the F1 is replaced by F2 . 并在某些时候用户单击按钮, F1F2代替。 The problem is when the user clicks on the back button: 问题是当用户单击后退按钮时:

  • 1st click: nothing happens 第一次点击:没有任何反应
  • 2nd click: goes from F2 to A1 ( F1 skipped) 第二次点击:从F2转到A1 (跳过F1

What I expect 我期望什么

  • 1st click: F2 -> F1 第一次点击: F2 > F1
  • 2nd click: F1 -> A1 第二次点击: F1 > A1

I have noticed that if I press back before F1 is replaced by F2: 我注意到如果在F1替换为F2之前按回车:

  • 1st click: F1 ->blank screen 第一次点击: F1 >黑屏
  • 2nd click: blank screen-> A1 第二次单击:黑屏-> A1

I think your problem may be caused by adding your first fragment to the backstack as well. 我认为您的问题也可能是由于将您的第一个片段也添加到了堆栈中引起的。 In your onCreate you call replaceFragment which adds it automatically. onCreate ,调用replaceFragment会自动添加它。 Just add the fragment manually without the addToBackStack call and use the replaceFragment function for all subsequent fragment transactions. 只需手动添加片段而无需addToBackStack调用,并对所有后续片段事务使用replaceFragment函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM