Reputation: 544
I need to override the physical button event with some logic but also the event itself of going back. The way I'm doing only works if I don't use any logic inside of the callback, I need to perform de logic and be able to going back.
This is how I'm doing.
val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
if(Hawk.contains("gtw")){
Hawk.delete("gtw");
}
}
I tried using isEnabled
but sill doesn't work!
Upvotes: 0
Views: 7369
Reputation: 1107
As much as I have understood from your question you need to do some logic whenever user presses back button from the app or from your device so for that :-
You need to override
activiy's lifecycle method named as onBackPressed()
. You can override that and write your required logic inside of that. It will be called whenever the user presses back button from the device itself or if you go back programatically from your activity
.
eg :-
override fun onBackPressed() {
super.onBackPressed()
// Your logic here
}
Update as mentioned in comments if you need to go back to your previous fragment from the current fragment then you need to get the callback in your current activity of that fragment. Now in that current activity you'll need to remove that fragment from your stack so you can check if there's any other fragments in the stack then you can simply pop
your current fragment or else you can execute the activity's
onBackpressed
itself.
You can refer this question on S.O and apply your own logic of handling backpressed in your fragments.
Upvotes: 2