-
Notifications
You must be signed in to change notification settings - Fork 0
/
NavFragmentOnBackPressedCallback.cs
61 lines (52 loc) · 2.64 KB
/
NavFragmentOnBackPressedCallback.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using Android.Content;
using AndroidX.Activity;
using AndroidX.Fragment.App;
using AndroidX.Navigation;
using AndroidX.Preference;
using com.companyname.NavigationGraph3.Fragments;
namespace com.companyname.NavigationGraph3
{
public class NavFragmentOnBackPressedCallback : OnBackPressedCallback
{
// Notes: OnBackPressedCallback was failing to work if instantiated in OnStart it would work in most instances, but fail on some Fragments OnDestroy where the callback is removed
// onBackPressedCallback?.Remove();
// base.OnDestroy();
// onBackPressedCallback could be null and therefore the callback was not removed which subsequently stuffed up other fragments.
// Moving the instantiation from OnStart to OnResume appears to have fixed the problem.
private readonly Fragment fragment;
private readonly bool animateFragments;
private NavOptions navOptions;
public NavFragmentOnBackPressedCallback(Fragment fragment, bool enabled) : base(enabled)
{
this.fragment = fragment;
// For animations only
ISharedPreferences sharedPreferences = PreferenceManager.GetDefaultSharedPreferences(this.fragment.Activity);
animateFragments = sharedPreferences.GetBoolean("use_animations", false);
}
public override void HandleOnBackPressed()
{
if (!animateFragments)
AnimationResource.Fader2();
else
AnimationResource.Slider();
navOptions = new NavOptions.Builder()
.SetLaunchSingleTop(true) // 22/05/2021 We do need this
.SetEnterAnim(AnimationResource.EnterAnimation)
.SetExitAnim(AnimationResource.ExitAnimation)
.SetPopEnterAnim(AnimationResource.PopEnterAnimation)
.SetPopExitAnim(AnimationResource.PopExitAnimation)
.Build();
// Mixture of top level and non top level fragments
if (fragment is HomeFragment homeFragment)
homeFragment.HandleBackPressed();
else if (fragment is GalleryFragment galleryFragment)
galleryFragment.HandleBackPressed(navOptions);
else if (fragment is SlideshowFragment slideshowFragment)
slideshowFragment.HandleBackPressed(navOptions);
else if (fragment is LeaderboardFragment leaderboardFragment)
leaderboardFragment.HandleBackPressed(navOptions);
else if (fragment is RegisterFragment registerFragment)
registerFragment.HandleBackPressed(navOptions);
}
}
}