我正在使用导航抽屉布局中的片段。每当在frame_container中看到任何其他片段时,我想按下后退按钮返回HomeFragment。如果主片段已经可见,我想完成MainActivity(navigation_drawer_activity)。帮我修正主要活动中的OnBackPressed代码。
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_home);
if(fragment!=null && fragment.isVisible()){
clearBackStack();
finish();
}else {
clearBackStack();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,new HomeFragment()).commit();
}
}
答案 0 :(得分:1)
这是解决方案。我从frame_container
找到了片段。
然后签入if语句。 if(fragment!=null && fragment instanceof HomeFragment && fragment.isVisible())
。这返回home_fragment
。
谢谢你的回答。
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame_container);
if(fragment!=null && fragment instanceof HomeFragment && fragment.isVisible()){
clearBackStack();
finish();
}else {
clearBackStack();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,new HomeFragment()).commit();
}
}
答案 1 :(得分:0)
试试这个
@Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
getSupportFragmentManager().popBackStackImmediate();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}