Android back button navigate to specific fragment

后端 未结 1 1566
名媛妹妹
名媛妹妹 2021-02-07 20:09

I have the navigation drawer menu structure presently setup to allow for going back to the previous fragmnet, with addToBackStack, when selecting the back button as:

<         


        
1条回答
  •  情歌与酒
    2021-02-07 21:05

    Take a look at this: FragmentManager.popBackStack(int, int)

    When you commit your fragment transaction, the method returns an identifier for that transaction. Save that int identifier:

    FragmentTransaction xfragmentTransaction = getFragmentManager().beingTransaction();
    xfragmentTransaction.replace(R.id.containerView, new MessageTabFragment());
    xfragmentTransaction.addToBackStack("MainActivity");
    int homeFragmentIdentifier = transaction.commit();
    

    then, in your onBackPressed() method, you can add either of the following lines:

    getFragmentManager().popBackStack(homeFragmentIdentifier, 0); // Exclusive
    

    or

    getFragmentManager().popBackStack("MainActivity", 0); // Exclusive
    

    This will pop the back stack all the way back to the supplied identifier. Alternatively, if you want to include the homeFragmentIdentifier in the "pop"ing, instead of 0 use FragmentManager.POP_BACK_STACK_INCLUSIVE for the 2nd parameter. You still must call FragmentTransaction.addToBackStack(). According to the docs:

    public abstract int commit () ... Returns the identifier of this transaction's back stack entry, if addToBackStack(String) had been called. Otherwise, returns a negative number.

    Also, if you set the tag of the fragment when adding it to the backstack, for example:

    transaction.add(yourFragment);
    transaction.addToBackStack("[YourFragmentTransactionTag]");
    

    You can use the alternate method: FragmentManager.popBackStack(String, int) by supplying the tag you used when adding the transaction to the backstack.

    getFragmentManager().popBackStack("[YourFragmentTransactionTag]", 0); 
    

    0 讨论(0)
提交回复
热议问题