Forked from qamarelsafadi/OnBackPressedAlternativeWay.kt
Created
April 4, 2023 10:09
-
-
Save nfaycel/6cec4f86bd8cbc6f8e011a1a417627a7 to your computer and use it in GitHub Desktop.
OnBackPressed Alternative way for fragments and activities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ----------------------------------------- Activity ------------------------------------------ */ | |
/* make sure you have at least 'androidx.activity:activity-ktx:1.6.0-rc01' at your dependencies | |
(just to let you know this dependency is not stable yet ) | |
*/ | |
implementation 'androidx.activity:activity-ktx:1.6.0-rc01' | |
fun AppCompatActivity.onBackPressed(isEnabled: Boolean, callback: () -> Unit) { | |
onBackPressedDispatcher.addCallback(this, | |
object : OnBackPressedCallback(isEnabled) { | |
override fun handleOnBackPressed() { | |
callback() | |
} | |
}) | |
} | |
// How To Use it : | |
class ExampleActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_example) | |
onBackPressed(true) { | |
// do what do you want when get back | |
} | |
} | |
} | |
/* --------------------------------------------- Fragments --------------------------------------------------- */ | |
// make sure you have at least androidx.activity:activity:1.0.0 at your dependencies | |
implementation 'androidx.activity:activity-ktx:1.0.0' | |
fun FragmentActivity.onBackPressed(callback: () -> Unit) { | |
onBackPressedDispatcher.addCallback(this, | |
object : OnBackPressedCallback(true) { | |
override fun handleOnBackPressed() { | |
callback() | |
} | |
} | |
) | |
} | |
// How To Use it : | |
class ExampleFragment : Fragment() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
requireActivity().onBackPressed { | |
// do what do you want when get back | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment