addToBackStack 没有导航回正确的片段

问题描述

你好,我正在尝试将一个 backstack 包含到 EditProfile Fragment 中,当按下 back 时它会返回到 Profile Fragment 但它会返回到 Home Fragment

如果你想要更多的代码参考,请告诉我我会更新 完整代码问题

配置文件片段

editProfileButton = relativeLayout.findViewById(R.id.edit_profile_button); // buuton to start editprofile fragment 
        editProfileButton.setonClickListener(v -> {
            Fragment edit_profile = new Edit_Profile();
            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container,edit_profile);
            transaction.addToBackStack(String.valueOf(new Profile_Fragment())); // i thinked this method of implementing string.valueof will navigate back to the given fragment but as you kNow it is not working
            transaction.commit();
        });

解决方法

我在 this 博文中找到了很好的解释。您可以尝试使用此代码并阅读更多相关信息。

public void addSubscreen(Fragment fragment) {
    getSupportManager()
        .beginTransaction()
        .replace(R.id.container,fragment)
        .addToBackStack(null)
        .commit();
    subscreensOnTheStack++;
}


public void popOffSubscreens() {
    while (subscreensOnTheStack > 0) {
        fragments.popBackStackImmediate();
    }
}