Replace Fragment with another on back button

后端 未结 3 770
北恋
北恋 2021-01-20 21:36

I\'m trying to override the Back Button because it\'s closing my app when I push on, I have different Fragments:

  • Fragment A: Index (When I press back button, i
3条回答
  •  终归单人心
    2021-01-20 21:47

    onBackPressed() and getSupportFragmentManager() are methods from the Activity class, not Fragment, so you have to implement this on the Activity and not the Fragment. If you want to implement a particular behaviour just for one fragment you can check what's the current visible fragment and then implement your behaviour. Like this:

    @Override
    public void onBackPressed(){
        MyFragment myFragment =   (MyFragment)getFragmentManager().findFragmentByTag("YOUR_FRAGMENT");
        if (myFragment != null && myFragment.isVisible()) {
           // the code for whatever behaviour you want goes here
        }
        else
           super.onBackPressed();
    }
    

    Another possible, probably simpler way would be to use some flag in the Activity that you activate when you add the fragment and then read from the onBackPressed().

    EDIT ON RESPONSE TO BENJY'S EDIT

    Notice that you're not exactly using the code I posted. You're using findFragmentById() which doesn't apply to every situation and I can't tell if it's right for your code. You should use findFragmentByTag which applies to any kind of fragment transaction. Just add a tag to your fragment when you do the transaction, like this:

     getSupportFragmentManager().beginTransaction()
                        .add(R.id.container, new PlaceholderFragment(), "FRAGMENT_TAG")
                        .commit();
    

    Then when you try to get back the Fragment in your onBackPressed(), you get it looking for that tag:

    PlaceholderFragment myFragment = (PlaceholderFragment) getSupportFragmentManager()
       .findFragmentByTag("FRAGMENT_TAG");
    

    Make this change it has to work.

提交回复
热议问题