Going back in Fragments by pressing the back button

前端 未结 1 1871
我寻月下人不归
我寻月下人不归 2021-01-22 18:28

I want to go back to another fragment by pressing the back button. I already read, that the addToBackStack (String tag) should help but it didn\'t really work.

相关标签:
1条回答
  • 2021-01-22 19:11

    I had the same situation before and I ended up with this solution. When you add or replace the Fragments, you need to add it to the backStack with a unique name. Then when the back button is pressed you can see which fragment was the active one with the method below inside the FragmentActivity that you created the Fragment.

    private String getCurrentFragmentName() {
    
        int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
    
        String fragmentName;
    
        if (backStackEntryCount > 0) {
            fragmentName = getSupportFragmentManager().getBackStackEntryAt(backStackEntryCount - 1).getName();
        } else {
            fragmentName = "";
        }
    
        return fragmentName;
    }
    

    and in on onKeyDown() method do the following.

        if (keyCode == KeyEvent.KEYCODE_BACK && getCurrentFragmentName().equals("your fragment name")) {
            // Handle back press for this case.
            return true;
    
        } else if (keyCode == KeyEvent.KEYCODE_BACK
                && getCurrentFragmentName().equals("your another fragment")) {
    
            // Handle back press for another Fragment
            return true;
    
        } else {
            return super.onKeyDown(keyCode, event);
        }
    

    And this is the Place how I add the Fragment with backStack

    transaction.addToBackStack("Your Fragment Name");
    
    0 讨论(0)
提交回复
热议问题