如何从活动返回到先前的片段? [英] How to go back to previous fragment from activity?
问题描述
我有一个带有导航抽屉的应用程序,可以切换片段.从其中一个片段的内部,我正在调用一项新的活动.当我在该活动中(在工具栏中)单击时,我想返回到先前选择的片段,但是它使我回到了第一个片段.我正在将片段添加到堆栈中,所以这应该不是问题.
I've got an app with nav drawer, which is switching fragments. From inside one of those fragments, I am calling a new activity. When I click back in this activity (in toolbar), I want to go back to previous selected fragment but instead it puts me back to first fragment. I am adding my fragment to back stack so this should not be a problem.
这是我已经尝试过的:
我在第2个活动中重写了onBackPressed方法,如下所示:
I have overriden the onBackPressed method in my 2nd activity like this:
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getFragmentManager().popBackStack();
}
}
它不起作用.我也将当前片段的索引保存在onsaveinstancestate方法内,并检索它但结果相同.我还尝试将当前片段始终放在变量中,然后尝试重新显示它,但仍然无法正常工作.我还能尝试什么吗?
It is not working. I also saved index of current fragment inside onsaveinstancestate method and retrieve it but same result. I also tried with always putting current fragment inside variable and try to reshow it but still, it does not work. Anything else I could try?
有趣的事实:如果我在底部面板内按回,它实际上会返回到先前的片段.
Fun fact: if I press back inside bottom panel, it does actually goes back to previous fragment.
这是我执行此操作的代码:
Here is my code for doing this:
private void replaceFragment(Fragment fragment)
{
if (fragment != null)
{
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.main_content, fragment)
.addToBackStack(null)
.commit();
}
}
如果saveInstanceState为null,则仅添加第一个片段,如下所示:
I add first fragment only, if savedInstanceState is null, like so:
if (savedInstanceState == null) {
// first time
mTitle = getResources().getString(R.string.home);
replaceFragment(HomeFragment.newInstance());
}
是的,所有这些都是在onCreate()方法中完成的.
And yes, all this is done inside onCreate() method.
推荐答案
我知道,人们仍在努力帮助我.此答案帮助我解决了我的问题: Android-从活动导航向上片段
I see, that people are still trying to help me. This answer helped me fix my problem: Android - Navigation Up from Activity to Fragment
这篇关于如何从活动返回到先前的片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!