Android: onBackPressed() in Fragments

Simple ways to implement onBackPressed in fragment android

Tejas Soni
3 min readMay 9, 2021
How to handle onBackPress in fragment by kotlin, latest way to handle backpress in fragments kotlin
Handle onBackPressed in Kotlin

People keep asking that is there any way to handle backpress in a fragment or do we have any override method of onBackPress similar to an activity in fragment also.

Now I will say yes we have.

I am going to share with you 3 ways to handle backpress in fragment. I can use this methods in Java as well as Kotlin. And I will be using kotlin

Let’s Start:

Method 1: Officially available in android lifecycle

override fun onAttach(context: Context) {
super.onAttach(context)
val callback: OnBackPressedCallback =
object : OnBackPressedCallback(true)
{
override fun handleOnBackPressed() {
// Leave empty do disable back press or
// write your code which you want
}
}
requireActivity().onBackPressedDispatcher.addCallback(
this,
callback
)
}

So, the above method OnBackPressedCallback is androidx.activity method.

This code registers activity onBackPressedDispatcher and gives you a callback in the current fragment.

Easy Right?

Let’s move forward and check some other ways

Method 2: Registering key Listener

So in this method, we will register key event press Like everyone knows that android devices have a back button on the screen right?

We will register that back button click listener, see below code

override fun onResume() {
super.onResume()
requireView().isFocusableInTouchMode = true
requireView().requestFocus()
requireView().setOnKeyListener { v, keyCode, event ->
if (event.action === KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
// Add your code here
true
} else false
}
}

In this method the parent view is focused and setOnKeyListener listens to the back button event

Here we are checking of event code so if the event code matches
keyCode == KeyEvent.KEYCODE_BACK then the condition will satisfy and you can add your code.

This is not similar to above code as if you don’t add code then it will not disable the backpress it will still work.
Let’s move to another method

Method 3: Mostly used method

This method is mostly use method by everyone till now, you know old is gold

So In this method we check in activity about the current displayed fragment in on backpress and write out code. I hope some you of you will get it.

In out activity we have override the method onbackPressed and in that we have checked the current active fragment and worked worked according to it
we will remove super.onbackPressed() method and use it when we wan to go back.

So as you will press the hard back button onBackPressed event will trigger and there we will check the current active fragment and write our code

override fun onBackPressed() {
val navHost = supportFragmentManager.findFragmentById(R.id.nav_login_fragment)
navHost?.let { navFragment ->
navFragment.childFragmentManager.primaryNavigationFragment?.let { fragment ->
if (fragment is LandingFragment) {
finish()
} else {
super.onBackPressed()
}
}
}
}

So as you can see here we have used Fragment container view for the navigation host in the layout

<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_login_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/login_nav" />

So, these are the 3 most simple ways to handle onbackPress event in android fragments. This code can also be done in java also.

I hope this was useful and you learn something.
You can write comments if any questions.
Thanks for reading. Follow me to check other topics

Check Here link

--

--