I would like the onBackPressedDispatcher
to absorb the back button press event. Sometimes but I don't see an option for it. Whats happening is that we are just today trying to upgrade to onBackPressedDispatcher
in androidX but we have already overridden onBackPressd
in activity. so when our onBackPressedDispatcher
calls OnBackPressedCallback
afterwards there is also a call to activities onBackPressed override. we don't want that. the onBackpressed
should be consumed on the spot. here is what I have so far:
const val TAG = "MyTag"
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
MyTester(this)
}
override fun onBackPressed() {
super.onBackPressed()
Log.v(TAG, "Activities class back button Pressed")
}
inner class MyTester(var activity: AppCompatActivity) {
init {
addBackCB()
}
fun addBackCB() {
var callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.v(TAG, "inner class MyTester back button")
}
}
activity.onBackPressedDispatcher.addCallback(activity, callback);
}
}
}
Which prints the following:
V/MyTag: inner class MyTester back button
V/MyTag: Activities class back button Pressed
If I don't call super.onBackPressed()
then the dispatcher does not even work. it needs that call.