我正在使用导航抽屉布局中的片段。每当在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();
    }

}

最佳答案

这是解决方案。我从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();
    }

}

10-08 03:32