@@ -9,6 +9,8 @@ import android.os.Bundle
9
9
import android.view.Menu
10
10
import android.view.MenuItem
11
11
import android.view.View
12
+ import androidx.activity.OnBackPressedCallback
13
+ import androidx.activity.addCallback
12
14
import androidx.appcompat.app.ActionBar
13
15
import androidx.fragment.app.FragmentManager
14
16
import androidx.fragment.app.FragmentTransaction
@@ -26,27 +28,29 @@ import com.wireguard.android.model.ObservableTunnel
26
28
class MainActivity : BaseActivity (), FragmentManager.OnBackStackChangedListener {
27
29
private var actionBar: ActionBar ? = null
28
30
private var isTwoPaneLayout = false
31
+ private var backPressedCallback: OnBackPressedCallback ? = null
29
32
30
- override fun onBackPressed () {
33
+ private fun handleBackPressed () {
31
34
val backStackEntries = supportFragmentManager.backStackEntryCount
32
35
// If the two-pane layout does not have an editor open, going back should exit the app.
33
36
if (isTwoPaneLayout && backStackEntries <= 1 ) {
34
37
finish()
35
38
return
36
39
}
37
- // Deselect the current tunnel on navigating back from the detail pane to the one-pane list.
38
- if (! isTwoPaneLayout && backStackEntries == 1 ) {
40
+
41
+ if (backStackEntries >= 1 )
39
42
supportFragmentManager.popBackStack()
43
+
44
+ // Deselect the current tunnel on navigating back from the detail pane to the one-pane list.
45
+ if (backStackEntries == 1 )
40
46
selectedTunnel = null
41
- return
42
- }
43
- super .onBackPressed()
44
47
}
45
48
46
49
override fun onBackStackChanged () {
50
+ val backStackEntries = supportFragmentManager.backStackEntryCount
51
+ backPressedCallback?.isEnabled = backStackEntries >= 1
47
52
if (actionBar == null ) return
48
53
// Do not show the home menu when the two-pane layout is at the detail view (see above).
49
- val backStackEntries = supportFragmentManager.backStackEntryCount
50
54
val minBackStackEntries = if (isTwoPaneLayout) 2 else 1
51
55
actionBar!! .setDisplayHomeAsUpEnabled(backStackEntries >= minBackStackEntries)
52
56
}
@@ -57,6 +61,7 @@ class MainActivity : BaseActivity(), FragmentManager.OnBackStackChangedListener
57
61
actionBar = supportActionBar
58
62
isTwoPaneLayout = findViewById<View ?>(R .id.master_detail_wrapper) != null
59
63
supportFragmentManager.addOnBackStackChangedListener(this )
64
+ backPressedCallback = onBackPressedDispatcher.addCallback(this ) { handleBackPressed() }
60
65
onBackStackChanged()
61
66
}
62
67
@@ -69,7 +74,7 @@ class MainActivity : BaseActivity(), FragmentManager.OnBackStackChangedListener
69
74
return when (item.itemId) {
70
75
android.R .id.home -> {
71
76
// The back arrow in the action bar should act the same as the back button.
72
- onBackPressed()
77
+ onBackPressedDispatcher. onBackPressed()
73
78
true
74
79
}
75
80
R .id.menu_action_edit -> {
0 commit comments