Is there a way in which we can implement onBackPressed()
in Android Fragment similar to the way in which we implement in Android Activity?
As the Fragment lifecycle do not have onBackPressed()
. Is there any other alternative method to over ride onBackPressed()
in Android 3.0 fragments?
In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so.
If you want to handle hardware Back key event than you have to do following code in your onActivityCreated() method of Fragment. You also need to check Action_Down or Action_UP event. If you will not check then onKey() Method will call 2 times.
I solved in this way override onBackPressed
in the Activity. All the FragmentTransaction
are addToBackStack
before commit:
@Override public void onBackPressed() { int count = getSupportFragmentManager().getBackStackEntryCount(); if (count == 0) { super.onBackPressed(); //additional code } else { getSupportFragmentManager().popBackStack(); } }
In my opinion the best solution is:
Create simple interface :
public interface IOnBackPressed { /** * If you return true the back press will not be taken into account, otherwise the activity will act naturally * @return true if your processing has priority if not false */ boolean onBackPressed(); }
And in your Activity
public class MyActivity extends Activity { @Override public void onBackPressed() { Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container); if (!(fragment instanceof IOnBackPressed) || !((IOnBackPressed) fragment).onBackPressed()) { super.onBackPressed(); } } ... }
Finally in your Fragment:
public class MyFragment extends Fragment implements IOnBackPressed{ @Override public boolean onBackPressed() { if (myCondition) { //action not popBackStack return true; } else { return false; } } }
interface IOnBackPressed { fun onBackPressed(): Boolean }
class MyActivity : AppCompatActivity() { override fun onBackPressed() { val fragment = this.supportFragmentManager.findFragmentById(R.id.main_container) (fragment as? IOnBackPressed)?.onBackPressed()?.not()?.let { super.onBackPressed() } } }
class MyFragment : Fragment(), IOnBackPressed { override fun onBackPressed(): Boolean { return if (myCondition) { //action not popBackStack true } else { false } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With