Skip to content

Instantly share code, notes, and snippets.

@cesarferreira
Created August 20, 2015 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cesarferreira/ffade381f0d977360e83 to your computer and use it in GitHub Desktop.
Save cesarferreira/ffade381f0d977360e83 to your computer and use it in GitHub Desktop.
Using onBackPressed() in Android Fragments
private final static String TAG_FRAGMENT = "TAG_FRAGMENT";
private void showFragment() {
final Myfragment fragment = new MyFragment();
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
transaction.addToBackStack(null);
transaction.commit();
}
@Override
public void onBackPressed() {
final Myfragment fragment = (Myfragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or not
super.onBackPressed();
}
}
@Sivasaran2003
Copy link

is there another way...isn't this method deprecated..

@cesarferreira
Copy link
Author

well this gist is 9 years old now.. so i imagine so

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment