handle onback pressed in fragemnt 2021 kotlin
To handle the onBackPressed event in a Kotlin fragment, you can follow these steps:
- Override the onBackPressed() method in your fragment class by extending the Fragment class and implementing the OnBackPressedCallback interface.
class MyFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireActivity().onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// Handle the back press event here
}
})
}
// Rest of your fragment code
}
- Inside the handleOnBackPressed() method, you can add the code to handle the back press event. For example, if you want to navigate to a previous fragment or perform some other action, you can do it here.
override fun handleOnBackPressed() {
// Handle the back press event here
// For example, navigate to a previous fragment
requireActivity().supportFragmentManager.popBackStack()
}
- If you want to disable the default behavior of the back button (e.g., closing the fragment or the activity), you can set the constructor parameter of OnBackPressedCallback to false.
requireActivity().onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(false) {
// ...
})
By following these steps, you can handle the onBackPressed event in a Kotlin fragment and perform the desired action when the back button is pressed within the fragment.