我的MainActivity在导航抽屉中有6个片段。现在,每当我在6个片段中的任何一个片段中,如果我按下后退按钮,我的应用程序就会退出。我想只退出第一个片段。如果我在其他片段中,那么如果我按回去,我希望它来到第一个片段,如果我再次按回来,那么我想要退出。 当它不在第一个位置时,我必须将片段替换为第一个片段。我知道。但是我怎样才能在onBackPressed中实现整体呢? 请帮忙 !!提前致谢。
答案 0 :(得分:1)
覆盖onBackPress
方法并添加此代码;
public void onBackPressed(){
int count = getFragmentManager().getBackStackEntryCount(); // if stack count is 0, it means no fragment left to pop back stack
if (count = 0) {
finish();
}
}
答案 1 :(得分:0)
您可以使用实例获取片段名称,我们可以检查它是否在家庭片段中的天气。将此代码粘贴到主活动类中的onBackPressed方法中。
Fragment f = getSupportFragmentManager().findFragmentById(R.id.frame_container);
/**
* Compare the instances based on fragment name to change the action bar
*/
if (f instanceof HomeFragment) {
finish();
System.exit(0);
} else {
super.onBackPressed();
}