Android - 防止打开前一个片段

Android - prevent to open previous fragment

伙计们。 这一定是一个愚蠢的问题,但我无法解决这个问题。我的情况是:我在我的 MainActivity 中有一个 BottomNavigation,我在其中导航了三个片段。我的问题是,当按下后退按钮(来自 android 底部导航工具栏)时,前一个片段打开但我希望应用程序关闭。所以我的问题是:我如何设法阻止以前的片段打开?

PS:我知道它与FragmentMananger back stack有关,但我不知道如何使用它。

PS2:抱歉英语不好。

覆盖 activity 中的 onBackPressed() 方法。

@Override
public void onBackPressed() {
    finish(); //This would close the app
}

警告。这将在用户按下后退的所有情况下关闭 activity。为了避免这种情况,您可能想创建这样的东西:

@Override
public void onBackPressed() {
    if(someCondition) {
        finish(); //This would close the activity
    }
    else {
        super.onBackPressed(); //Fallbacks to default Android implementation
    }
}

片段在后台。

编辑:

使用 FragmentTransaction 并使用 addToBackStack (null)

//  Create new fragment and transaction
    Fragment newFragment = new  ExampleFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

// Commit the transaction
    transaction.commit();