Skip to content

Commit

Permalink
improvement(nav-drawer): back dispatcher ordering
Browse files Browse the repository at this point in the history
This introduces `setupBackPressedCallbacks` so we can
control whether we want nav drawer dispatchers to take priority
(normally we do)

Issue 14558
  • Loading branch information
david-allison authored and mikehardy committed Jan 26, 2025
1 parent e5e3c5a commit 8dfff03
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions AnkiDroid/src/main/java/com/ichi2/anki/NavigationDrawerActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import android.view.MenuItem
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.CallSuper
import androidx.annotation.LayoutRes
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.ActionBarDrawerToggle
Expand Down Expand Up @@ -73,6 +74,14 @@ abstract class NavigationDrawerActivity :
*/
private var pendingRunnable: Runnable? = null

private val drawerBackCallback =
object : OnBackPressedCallback(enabled = false) {
override fun handleOnBackPressed() {
Timber.d("drawerBackCallback")
closeDrawer()
}
}

override fun setContentView(
@LayoutRes layoutResID: Int,
) {
Expand Down Expand Up @@ -141,13 +150,7 @@ abstract class NavigationDrawerActivity :
// Decide which action to take when the navigation button is tapped.
toolbar.setNavigationOnClickListener { onNavigationPressed() }
}
val drawerBackCallback =
object : OnBackPressedCallback(isDrawerOpen) {
override fun handleOnBackPressed() {
closeDrawer()
}
}
onBackPressedDispatcher.addCallback(this, drawerBackCallback)
setupBackPressedCallbacks()
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
drawerToggle =
Expand Down Expand Up @@ -190,6 +193,17 @@ abstract class NavigationDrawerActivity :
this.sendBroadcast(intent)
}

/**
* A method which allows control of the ordering of adding the [OnBackPressedCallback]
* for the drawer.
*
* Typically, call super after initialization code, so the drawer takes priority
*/
@CallSuper
protected open fun setupBackPressedCallbacks() {
onBackPressedDispatcher.addCallback(this, drawerBackCallback)
}

/**
* Sets selected navigation drawer item
*/
Expand Down

0 comments on commit 8dfff03

Please sign in to comment.