I\'m trying to override the Back Button because it\'s closing my app when I push on, I have different Fragments:
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.