Skip to content

Commit

Permalink
Fix onBackPressed() deprecation in NavigationDrawerActivity
Browse files Browse the repository at this point in the history
Created a back callback for closing the drawer and connected it to the
drawer's listener to enable and disable it dynamically.

The code was added to initNavigationDrawer method which all screens
that appear in the drawer(DeckPicker, CardBrowser and Reviewer) call
in onCreate().

Having both the drawer opening and the back gesture happening on
swipe from the screen's left edge isn't great.
  • Loading branch information
lukstbit committed Dec 9, 2024
1 parent 13d35ab commit 4a5543d
Showing 1 changed file with 9 additions and 12 deletions.
21 changes: 9 additions & 12 deletions AnkiDroid/src/main/java/com/ichi2/anki/NavigationDrawerActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.LayoutRes
import androidx.annotation.VisibleForTesting
Expand Down Expand Up @@ -142,6 +143,12 @@ 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(drawerBackCallback)
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
drawerToggle = object : ActionBarDrawerToggle(
Expand All @@ -154,7 +161,7 @@ abstract class NavigationDrawerActivity :
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
invalidateOptionsMenu()

drawerBackCallback.isEnabled = false
// If animations are disabled, this is executed before onNavigationItemSelected is called
// PERF: May be able to reduce this delay
HandlerUtils.postDelayedOnNewHandler({
Expand All @@ -168,6 +175,7 @@ abstract class NavigationDrawerActivity :
override fun onDrawerOpened(drawerView: View) {
super.onDrawerOpened(drawerView)
invalidateOptionsMenu()
drawerBackCallback.isEnabled = true
}
}
if (drawerLayout is ClosableDrawerLayout) {
Expand Down Expand Up @@ -265,17 +273,6 @@ abstract class NavigationDrawerActivity :
}
}

@Suppress("deprecation") // onBackPressed
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
if (isDrawerOpen) {
Timber.i("Back key pressed")
closeDrawer()
} else {
super.onBackPressed()
}
}

/**
* Called, when navigation button of the action bar is pressed.
* Design pattern: template method. Subclasses can override this to define their own behaviour.
Expand Down

0 comments on commit 4a5543d

Please sign in to comment.