在底部导航中维护BackStack

时间:2018-11-18 19:55:01

标签: android android-fragments

我在我的Android应用中使用bottomNavigation。我有5个片段A,B,C,D,E。片段B包含另一个片段B1。当我在片段B1上按下时,它将关闭应用程序。从片段B1向后压时如何移动到片段B。

这是我的代码

 bottomNavigationView.setOnNavigationItemSelectedListener(
                item -> {
                    Fragment fragment = null;

                    switch (item.getItemId()) {
                        case R.id.A:
                            fragment = new A();
                            break;
                        case R.id.B:
                            fragment = new B();
                            break;
                        case R.id.C:
                            fragment = new C();
                            break;

                        case R.id.D:
                           fragment = new D();
                           break;

                        case R.id.E:
                            fragment = new E();
                            break;

                    }
                    return loadFragment(fragment);

                });


private boolean loadFragment(Fragment fragment) {
    //switching fragment
    if (fragment != null) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.main_fragment, fragment)
                .commit();
         return true;
    }
    return false;
}

1 个答案:

答案 0 :(得分:2)

在打开B1片段时使用此

private boolean loadFragmentB1(Fragment fragment) {
//switching fragment
if (fragment != null) {
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.main_fragment, fragment)
            .commit();
     return true;

打开B1以外的其他片段时,请使用此

private boolean loadFragment(Fragment fragment) {
    //switching fragment
    if (fragment != null) {
        getSupportFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.main_fragment, fragment)
                .commit();
        return true;
    }
    return false;

}

并在活动时像这样覆盖onBackPressed

@Override
public void onBackPressed(){
    if (getSupportFragmentManager().getBackStackEntryCount() != 0) {
        getSupportFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
        finish();
    }
}