我的问题是,我有一个活动和一个片段,从活动打开该片段但是当我按下按钮时它关闭应用程序。 我尝试使用此代码。
case R.id.button_contact:
Fragment fragment = new FragmentContact();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,fragment).addToBackStack("Frag1").commit();
break;
@Override
public void onBackPressed() {
getSupportFragmentManager().popBackStackImmediate("Frag1",0);
super.onBackPressed();
}
答案 0 :(得分:5)
我假设您只想删除片段并保留活动?
在这种情况下,将onBackPressed方法修改为
@Override
public void onBackPressed() {
if (getSupportFragmentManager().findFragmentByTag("Frag1") != null) {
getSupportFragmentManager().popBackStackImmediate("Frag1",0);
} else {
super.onBackPressed();
}
}
这将从活动中删除片段(如果已添加),如果不添加,则后退按钮将正常运行并销毁活动。
答案 1 :(得分:1)
只需从onBackPressed()中删除此行。
getSupportFragmentManager().popBackStackImmediate("Frag1",0);
它的工作。
答案 2 :(得分:1)
你可以这样做。它适用于您的堆栈:
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
如果有任何片段,这段代码将弹出堆栈。否则后退按钮将关闭活动
答案 3 :(得分:1)
这两条线正在做什么:
1). getSupportFragmentManager().popBackStackImmediate("Frag1",0);
As you are adding you fragment in activity backstack, so when you are calling on back press,
it remove fragment from stack, now in your stack activity is left, means stack size is one.
2). super.onBackPressed();
I think you are aware of calling super.onbackpress funcionality, here it will finish
your activity and stack size is 0 now, and app will close immidately if stack size is 0.
所以你必须删除super.onbackpress()方法。