-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
MvxAndroidViewPresenter.cs
1163 lines (943 loc) · 45.8 KB
/
MvxAndroidViewPresenter.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MS-PL license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using Android.Views;
using AndroidX.ViewPager.Widget;
using Google.Android.Material.Tabs;
using Java.Lang;
using MvvmCross.Exceptions;
using MvvmCross.Logging;
using MvvmCross.Platforms.Android.Core;
using MvvmCross.Platforms.Android.Presenters.Attributes;
using MvvmCross.Platforms.Android.Views;
using MvvmCross.Platforms.Android.Views.Fragments;
using MvvmCross.Platforms.Android.Views.ViewPager;
using MvvmCross.Presenters;
using MvvmCross.Presenters.Attributes;
using MvvmCross.Presenters.Hints;
using MvvmCross.ViewModels;
using MvvmCross.Views;
using Activity = AndroidX.AppCompat.App.AppCompatActivity;
using DialogFragment = AndroidX.Fragment.App.DialogFragment;
using Fragment = AndroidX.Fragment.App.Fragment;
using FragmentManager = AndroidX.Fragment.App.FragmentManager;
using FragmentTransaction = AndroidX.Fragment.App.FragmentTransaction;
namespace MvvmCross.Platforms.Android.Presenters
{
#nullable enable
public class MvxAndroidViewPresenter : MvxAttributeViewPresenter, IMvxAndroidViewPresenter
{
public const string ViewModelRequestBundleKey = "__mvxViewModelRequest";
public const string SharedElementsBundleKey = "__sharedElementsKey";
private readonly Lazy<IMvxAndroidCurrentTopActivity> _androidCurrentTopActivity =
new Lazy<IMvxAndroidCurrentTopActivity>(() => Mvx.IoCProvider.Resolve<IMvxAndroidCurrentTopActivity>());
private readonly Lazy<IMvxAndroidActivityLifetimeListener> _activityLifetimeListener =
new Lazy<IMvxAndroidActivityLifetimeListener>(() => Mvx.IoCProvider.Resolve<IMvxAndroidActivityLifetimeListener>());
private readonly Lazy<IMvxNavigationSerializer> _navigationSerializer =
new Lazy<IMvxNavigationSerializer>(() => Mvx.IoCProvider.Resolve<IMvxNavigationSerializer>());
private readonly Lazy<IMvxLog> _logger =
new Lazy<IMvxLog>(() => Mvx.IoCProvider.Resolve<IMvxLog>());
protected IEnumerable<Assembly> AndroidViewAssemblies { get; set; }
protected MvxViewModelRequest? PendingRequest { get; set; }
protected virtual FragmentManager? CurrentFragmentManager
{
get
{
if (CurrentActivity.IsActivityDead())
return null;
return CurrentActivity!.SupportFragmentManager;
}
}
protected virtual Activity? CurrentActivity =>
_androidCurrentTopActivity.Value?.Activity as Activity;
protected IMvxAndroidActivityLifetimeListener ActivityLifetimeListener =>
_activityLifetimeListener.Value;
protected IMvxNavigationSerializer NavigationSerializer =>
_navigationSerializer.Value;
public MvxAndroidViewPresenter(IEnumerable<Assembly> androidViewAssemblies)
{
AndroidViewAssemblies = androidViewAssemblies;
ActivityLifetimeListener.ActivityChanged += ActivityLifetimeListenerOnActivityChanged;
}
protected virtual void ActivityLifetimeListenerOnActivityChanged(object sender, MvxActivityEventArgs e)
{
if (e.ActivityState == MvxActivityState.OnResume && PendingRequest != null)
{
Show(PendingRequest);
PendingRequest = null;
}
else if (e.ActivityState == MvxActivityState.OnCreate && e.Extras is Bundle savedBundle)
{
//TODO: Restore fragments from bundle
}
else if (e.ActivityState == MvxActivityState.OnSaveInstanceState && e.Extras is Bundle outBundle)
{
//TODO: Save fragments into bundle
}
else if (e.ActivityState == MvxActivityState.OnDestroy)
{
//TODO: Should be check for Fragments on this Activity and destroy them?
}
}
protected Type GetAssociatedViewModelType(Type fromFragmentType)
{
var viewModelType = ViewModelTypeFinder?.FindTypeOrNull(fromFragmentType);
return viewModelType ?? fromFragmentType.GetBasePresentationAttributes().First().ViewModelType;
}
public override void RegisterAttributeTypes()
{
AttributeTypesToActionsDictionary.Register<MvxActivityPresentationAttribute>(ShowActivity, CloseActivity);
AttributeTypesToActionsDictionary.Register<MvxFragmentPresentationAttribute>(ShowFragment, CloseFragment);
AttributeTypesToActionsDictionary.Register<MvxDialogFragmentPresentationAttribute>(ShowDialogFragment, CloseFragmentDialog);
AttributeTypesToActionsDictionary.Register<MvxTabLayoutPresentationAttribute>(ShowTabLayout, CloseViewPagerFragment);
AttributeTypesToActionsDictionary.Register<MvxViewPagerFragmentPresentationAttribute>(ShowViewPagerFragment, CloseViewPagerFragment);
}
public override MvxBasePresentationAttribute GetPresentationAttribute(MvxViewModelRequest request)
{
ValidateArguments(request);
var viewType = ViewsContainer?.GetViewType(request.ViewModelType);
if (viewType == null)
throw new InvalidOperationException($"Could not get view type for ViewModel Type: {request.ViewModelType}");
var overrideAttribute = GetOverridePresentationAttribute(request, viewType);
if (overrideAttribute != null)
return overrideAttribute;
IList<MvxBasePresentationAttribute> attributes =
viewType.GetCustomAttributes<MvxBasePresentationAttribute>(true).ToList();
if (attributes.Count > 0)
{
MvxBasePresentationAttribute? attribute = null;
if (attributes.Count > 1)
{
var fragmentAttributes = attributes.OfType<MvxFragmentPresentationAttribute>().ToArray();
// check if fragment can be displayed as child fragment first
attribute = GetAttributeForFragmentChildPresentation(fragmentAttributes);
// if attribute is still null, check if fragment can be displayed in current activity
attribute ??= GetAttributeForFragmentPresentation(fragmentAttributes);
}
// fallback to first attribute
attribute ??= attributes[0];
attribute.ViewType = viewType;
return attribute;
}
return CreatePresentationAttribute(request.ViewModelType, viewType);
}
private MvxBasePresentationAttribute? GetAttributeForFragmentPresentation(
IEnumerable<MvxFragmentPresentationAttribute> fragmentAttributes)
{
MvxBasePresentationAttribute? attribute = null;
var currentActivityHostViewModelType = GetCurrentActivityViewModelType();
foreach (var item in fragmentAttributes.Where(
att => att.ActivityHostViewModelType != null))
{
if (CurrentActivity.IsActivityDead())
break;
if (CurrentActivity!.FindViewById(item.FragmentContentId) != null &&
item.ActivityHostViewModelType == currentActivityHostViewModelType)
{
attribute = item;
break;
}
}
return attribute;
}
private MvxBasePresentationAttribute? GetAttributeForFragmentChildPresentation(
IEnumerable<MvxFragmentPresentationAttribute> fragmentAttributes)
{
MvxBasePresentationAttribute? attribute = null;
foreach (var item in fragmentAttributes.Where(
att => att.FragmentHostViewType != null))
{
var fragment = GetFragmentByViewType(item.FragmentHostViewType);
// if the fragment exists, and is on top, then use the current attribute
if (fragment?.IsVisible != true || fragment.View.FindViewById(item.FragmentContentId) == null)
continue;
attribute = item;
break;
}
return attribute;
}
public override MvxBasePresentationAttribute CreatePresentationAttribute(Type? viewModelType, Type? viewType)
{
if (viewType == null)
throw new ArgumentNullException(nameof(viewType));
if (viewType.IsSubclassOf(typeof(DialogFragment)))
{
_logger.Value?.Trace("PresentationAttribute not found for {0}. Assuming DialogFragment presentation", viewType.Name);
return new MvxDialogFragmentPresentationAttribute() { ViewType = viewType, ViewModelType = viewModelType };
}
if (viewType.IsSubclassOf(typeof(Fragment)))
{
_logger.Value?.Trace("PresentationAttribute not found for {0}. Assuming Fragment presentation", viewType.Name);
return new MvxFragmentPresentationAttribute(GetCurrentActivityViewModelType(), global::Android.Resource.Id.Content) { ViewType = viewType, ViewModelType = viewModelType };
}
if (viewType.IsSubclassOf(typeof(Activity)))
{
_logger.Value?.Trace("PresentationAttribute not found for {0}. Assuming Activity presentation", viewType.Name);
return new MvxActivityPresentationAttribute() { ViewType = viewType, ViewModelType = viewModelType };
}
throw new InvalidOperationException($"Don't know how to create a presentation attribute for type {viewType}");
}
public override Task<bool> ChangePresentation(MvxPresentationHint hint)
{
if (hint == null)
throw new ArgumentNullException(nameof(hint));
if (hint is MvxPagePresentationHint pagePresentationHint)
{
var result = ChangePagePresentation(pagePresentationHint);
return Task.FromResult(result);
}
return base.ChangePresentation(hint);
}
private bool ChangePagePresentation(MvxPagePresentationHint pagePresentationHint)
{
var request = new MvxViewModelRequest(pagePresentationHint.ViewModel);
var attribute = GetPresentationAttribute(request);
if (attribute is MvxViewPagerFragmentPresentationAttribute pagerFragmentAttribute)
{
var viewPager = FindViewPagerInFragmentPresentation(pagerFragmentAttribute);
if (viewPager?.Adapter is MvxCachingFragmentStatePagerAdapter adapter)
{
var fragmentInfo = FindFragmentInfoFromAttribute(pagerFragmentAttribute, adapter);
var index = adapter.FragmentsInfo.IndexOf(fragmentInfo);
if (index < 0)
{
_logger.Value?.Trace("Did not find ViewPager index for {0}, skipping presentation change...",
pagerFragmentAttribute.Tag);
return true;
}
viewPager.SetCurrentItem(index, true);
return true;
}
}
return false;
}
protected virtual ViewPager? FindViewPagerInFragmentPresentation(
MvxViewPagerFragmentPresentationAttribute pagerFragmentAttribute)
{
ValidateArguments(pagerFragmentAttribute);
ViewPager? viewPager = null;
// check for a ViewPager inside a Fragment
if (pagerFragmentAttribute.FragmentHostViewType != null)
{
var fragment = GetFragmentByViewType(pagerFragmentAttribute.FragmentHostViewType);
viewPager = fragment?.View.FindViewById<ViewPager>(pagerFragmentAttribute.ViewPagerResourceId);
}
// check for a ViewPager inside an Activity
if (viewPager == null && pagerFragmentAttribute.ActivityHostViewModelType != null &&
CurrentActivity.IsActivityAlive())
{
viewPager = CurrentActivity!.FindViewById<ViewPager>(pagerFragmentAttribute.ViewPagerResourceId);
}
return viewPager;
}
protected Type? GetCurrentActivityViewModelType()
{
Type? currentActivityType = null;
if (CurrentActivity.IsActivityAlive())
currentActivityType = CurrentActivity!.GetType();
var activityViewModelType = ViewModelTypeFinder?.FindTypeOrNull(currentActivityType);
return activityViewModelType;
}
#region Show implementations
protected virtual Task<bool> ShowActivity(
Type view,
MvxActivityPresentationAttribute attribute,
MvxViewModelRequest request)
{
ValidateArguments(view, attribute, request);
var intent = CreateIntentForRequest(request);
if (attribute.Extras != null)
intent.PutExtras(attribute.Extras);
ShowIntent(intent, CreateActivityTransitionOptions(intent, attribute, request));
return Task.FromResult(true);
}
protected virtual Bundle CreateActivityTransitionOptions(
Intent intent, MvxActivityPresentationAttribute attribute, MvxViewModelRequest request)
{
ValidateArguments(attribute, request);
if (intent == null)
throw new ArgumentNullException(nameof(intent));
var bundle = Bundle.Empty!;
if (CurrentActivity.IsActivityAlive() &&
CurrentActivity is IMvxAndroidSharedElements sharedElementsActivity &&
Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
var (elements, transitionElementPairs) =
GetTransitionElements(attribute, request, sharedElementsActivity);
if (transitionElementPairs.Count == 0)
{
_logger.Value?.Warn("No transition elements are provided");
return bundle;
}
var transitionElementsBundle = CreateTransitionElementsBundle(intent, transitionElementPairs, elements);
if (transitionElementsBundle != null)
return transitionElementsBundle;
}
else
{
_logger.Value?.Warn("Shared element transition requires Android v21+.");
}
return bundle;
}
private Bundle? CreateTransitionElementsBundle(
Intent intent, IEnumerable<Pair> transitionElementPairs, IEnumerable<string> elements)
{
var activityOptions = ActivityOptions.MakeSceneTransitionAnimation(
CurrentActivity, transitionElementPairs.ToArray());
if (activityOptions == null)
return null;
intent.PutExtra(SharedElementsBundleKey, string.Join("|", elements));
var activityOptionsBundle = activityOptions.ToBundle();
return activityOptionsBundle;
}
private (List<string> elements, List<Pair> transitionElementPairs) GetTransitionElements(
MvxBasePresentationAttribute attribute, MvxViewModelRequest request,
IMvxAndroidSharedElements sharedElementsActivity)
{
var elements = new List<string>();
var transitionElementPairs = new List<Pair>();
foreach (var (key, value) in sharedElementsActivity.FetchSharedElementsToAnimate(attribute, request))
{
var transitionName = value.GetTransitionNameSupport();
if (!string.IsNullOrEmpty(transitionName))
{
var pair = Pair.Create(value, transitionName);
if (pair != null)
{
transitionElementPairs.Add(pair);
elements.Add($"{key}:{transitionName}");
}
}
else
{
_logger.Value?.Warn("A XML transitionName is required in order to transition a control when navigating.");
}
}
return (elements, transitionElementPairs);
}
protected virtual Intent CreateIntentForRequest(MvxViewModelRequest? request)
{
var requestTranslator = Mvx.IoCProvider.Resolve<IMvxAndroidViewModelRequestTranslator>();
if (request is MvxViewModelInstanceRequest viewModelInstanceRequest)
{
var intentWithKey = requestTranslator.GetIntentWithKeyFor(
viewModelInstanceRequest.ViewModelInstance,
viewModelInstanceRequest
);
return intentWithKey.intent;
}
return requestTranslator.GetIntentFor(request);
}
protected virtual void ShowIntent(Intent intent, Bundle? bundle)
{
if (intent == null)
throw new ArgumentNullException(nameof(intent));
var activity = CurrentActivity;
if (activity.IsActivityDead())
{
_logger.Value?.Warn("Cannot Resolve current top activity. Creating new activity from Application Context");
intent.AddFlags(ActivityFlags.NewTask);
StartActivity(Application.Context, intent, bundle);
return;
}
StartActivity(activity!, intent, bundle);
}
private static void StartActivity(Context context, Intent intent, Bundle? bundle)
{
if (bundle != null)
{
context.StartActivity(intent, bundle);
}
else
{
context.StartActivity(intent);
}
}
protected virtual void ShowHostActivity(MvxFragmentPresentationAttribute attribute)
{
ValidateArguments(attribute);
var viewType = ViewsContainer?.GetViewType(attribute.ActivityHostViewModelType);
if (viewType?.IsSubclassOf(typeof(Activity)) != true)
throw new MvxException("The host activity doesn't inherit Activity");
var hostViewModelRequest = MvxViewModelRequest.GetDefaultRequest(attribute.ActivityHostViewModelType);
if (PendingRequest != null)
hostViewModelRequest.PresentationValues = PendingRequest.PresentationValues;
Show(hostViewModelRequest);
}
protected virtual Task<bool> ShowFragment(
Type view,
MvxFragmentPresentationAttribute attribute,
MvxViewModelRequest request)
{
ValidateArguments(view, attribute, request);
// if attribute has a Fragment Host, then show it as nested and return
if (attribute.FragmentHostViewType != null)
{
ShowNestedFragment(view, attribute, request);
return Task.FromResult(true);
}
// if there is no Activity host associated, assume is the current activity
if (attribute.ActivityHostViewModelType == null)
attribute.ActivityHostViewModelType = GetCurrentActivityViewModelType();
var currentHostViewModelType = GetCurrentActivityViewModelType();
if (attribute.ActivityHostViewModelType != currentHostViewModelType)
{
_logger.Value?.Trace("Activity host with ViewModelType {0} is not CurrentTopActivity. Showing Activity before showing Fragment for {1}",
attribute.ActivityHostViewModelType, attribute.ViewModelType);
PendingRequest = request;
ShowHostActivity(attribute);
}
else if (CurrentActivity.IsActivityAlive())
{
if (CurrentActivity!.FindViewById(attribute!.FragmentContentId) == null)
throw new InvalidOperationException("FrameLayout to show Fragment not found");
PerformShowFragmentTransaction(CurrentActivity.SupportFragmentManager, attribute, request);
}
return Task.FromResult(true);
}
protected virtual void ShowNestedFragment(
Type view,
MvxFragmentPresentationAttribute attribute,
MvxViewModelRequest request)
{
ValidateArguments(view, attribute, request);
// current implementation only supports one level of nesting
var fragmentHost = GetFragmentByViewType(attribute!.FragmentHostViewType);
if (fragmentHost == null)
throw new InvalidOperationException($"Fragment host not found when trying to show View {view.Name} as Nested Fragment");
if (!fragmentHost.IsVisible)
_logger.Value?.Warn("Fragment host is not visible when trying to show View {0} as Nested Fragment", view!.Name);
PerformShowFragmentTransaction(fragmentHost.ChildFragmentManager, attribute, request);
}
protected virtual void PerformShowFragmentTransaction(
FragmentManager fragmentManager,
MvxFragmentPresentationAttribute attribute,
MvxViewModelRequest request)
{
ValidateArguments(attribute, request);
if (fragmentManager == null)
throw new ArgumentNullException(nameof(fragmentManager));
var fragmentName = attribute.ViewType.FragmentJavaName();
IMvxFragmentView? fragmentView = null;
if (attribute.IsCacheableFragment)
{
fragmentView = (IMvxFragmentView)fragmentManager.FindFragmentByTag(fragmentName);
}
fragmentView ??= CreateFragment(fragmentManager, attribute, attribute.ViewType);
var fragment = fragmentView.ToFragment();
if (fragment == null)
throw new MvxException($"Fragment {fragmentName} is null. Cannot perform Fragment Transaction.");
// MvxNavigationService provides an already instantiated ViewModel here
if (request is MvxViewModelInstanceRequest instanceRequest)
{
fragmentView.ViewModel = instanceRequest.ViewModelInstance;
}
// save MvxViewModelRequest in the Fragment's Arguments
#pragma warning disable CA2000 // Dispose objects before losing scope
var bundle = new Bundle();
#pragma warning restore CA2000 // Dispose objects before losing scope
var serializedRequest = NavigationSerializer.Serializer.SerializeObject(request);
bundle.PutString(ViewModelRequestBundleKey, serializedRequest);
if (fragment.Arguments == null)
{
fragment.Arguments = bundle;
}
else
{
fragment.Arguments.Clear();
fragment.Arguments.PutAll(bundle);
}
var ft = fragmentManager.BeginTransaction();
OnBeforeFragmentChanging(ft, fragment, attribute, request);
if (attribute.AddToBackStack)
ft.AddToBackStack(fragmentName);
OnFragmentChanging(ft, fragment, attribute, request);
if (attribute.AddFragment && fragment.IsAdded)
{
ft.Show(fragment);
}
else if (attribute.AddFragment)
{
ft.Add(attribute.FragmentContentId, fragment, fragmentName);
}
else
{
ft.Replace(attribute.FragmentContentId, fragment, fragmentName);
}
ft.CommitAllowingStateLoss();
OnFragmentChanged(ft, fragment, attribute, request);
}
protected virtual void OnBeforeFragmentChanging(
FragmentTransaction fragmentTransaction,
Fragment fragment,
MvxFragmentPresentationAttribute attribute,
MvxViewModelRequest request)
{
if (fragmentTransaction == null)
throw new ArgumentNullException(nameof(fragmentTransaction));
if (fragment == null)
throw new ArgumentNullException(nameof(fragment));
ValidateArguments(attribute, request);
if (CurrentActivity.IsActivityAlive() && CurrentActivity is IMvxAndroidSharedElements sharedElementsActivity)
{
var elements = new List<string>();
foreach (var (key, value) in sharedElementsActivity.FetchSharedElementsToAnimate(attribute, request))
{
var transitionName = value.GetTransitionNameSupport();
if (!string.IsNullOrEmpty(transitionName))
{
fragmentTransaction.AddSharedElement(value, transitionName);
elements.Add($"{key}:{transitionName}");
}
else
{
_logger.Value?.Warn("A XML transitionName is required in order to transition a control when navigating.");
}
}
if (elements.Count > 0)
fragment.Arguments.PutString(SharedElementsBundleKey, string.Join("|", elements));
}
if (!attribute.EnterAnimation.Equals(int.MinValue) && !attribute.ExitAnimation.Equals(int.MinValue))
{
if (!attribute.PopEnterAnimation.Equals(int.MinValue) && !attribute.PopExitAnimation.Equals(int.MinValue))
fragmentTransaction.SetCustomAnimations(attribute.EnterAnimation, attribute.ExitAnimation, attribute.PopEnterAnimation, attribute.PopExitAnimation);
else
fragmentTransaction.SetCustomAnimations(attribute.EnterAnimation, attribute.ExitAnimation);
}
if (attribute.TransitionStyle != int.MinValue)
fragmentTransaction.SetTransitionStyle(attribute.TransitionStyle);
}
protected virtual void OnFragmentChanged(FragmentTransaction? fragmentTransaction, Fragment? fragment, MvxFragmentPresentationAttribute? attribute, MvxViewModelRequest? request)
{
}
protected virtual void OnFragmentChanging(FragmentTransaction? fragmentTransaction, Fragment? fragment, MvxFragmentPresentationAttribute? attribute, MvxViewModelRequest? request)
{
}
protected virtual void OnFragmentPopped(FragmentTransaction? fragmentTransaction, Fragment? fragment, MvxFragmentPresentationAttribute? attribute)
{
}
protected virtual Task<bool> ShowDialogFragment(
Type view,
MvxDialogFragmentPresentationAttribute attribute,
MvxViewModelRequest request)
{
ValidateArguments(view, attribute, request);
if (CurrentActivity == null)
throw new InvalidOperationException("CurrentActivity is null");
if (CurrentFragmentManager == null)
throw new InvalidOperationException("CurrentFragmentManager is null. Cannot create Fragment Transaction.");
var fragmentName = attribute.ViewType.FragmentJavaName();
IMvxFragmentView mvxFragmentView = CreateFragment(CurrentActivity.SupportFragmentManager, attribute, attribute.ViewType);
var dialog = (DialogFragment)mvxFragmentView;
// MvxNavigationService provides an already instantiated ViewModel here,
// therefore just assign it
if (request is MvxViewModelInstanceRequest instanceRequest)
{
mvxFragmentView.ViewModel = instanceRequest.ViewModelInstance;
}
else
{
mvxFragmentView.LoadViewModelFrom(request, null);
}
dialog.Cancelable = attribute.Cancelable;
var ft = CurrentFragmentManager.BeginTransaction();
OnBeforeFragmentChanging(ft, dialog, attribute, request);
if (attribute.AddToBackStack)
ft.AddToBackStack(fragmentName);
OnFragmentChanging(ft, dialog, attribute, request);
dialog.Show(ft, fragmentName);
OnFragmentChanged(ft, dialog, attribute, request);
return Task.FromResult(true);
}
protected virtual Task<bool> ShowViewPagerFragment(
Type view,
MvxViewPagerFragmentPresentationAttribute attribute,
MvxViewModelRequest request)
{
ValidateArguments(view, attribute, request);
// if the attribute doesn't supply any host, assume current activity!
if (attribute.FragmentHostViewType == null && attribute.ActivityHostViewModelType == null)
attribute.ActivityHostViewModelType = GetCurrentActivityViewModelType();
ViewPager? viewPager = null;
FragmentManager? fragmentManager = null;
// check for a ViewPager inside a Fragment
if (attribute.FragmentHostViewType != null)
{
var fragment = GetFragmentByViewType(attribute.FragmentHostViewType);
if (fragment == null)
throw new MvxException("Fragment not found", attribute.FragmentHostViewType.Name);
if (fragment.View == null)
throw new MvxException("Fragment.View is null. Please consider calling Navigate later in your code",
attribute!.FragmentHostViewType.Name);
viewPager = fragment.View.FindViewById<ViewPager>(attribute.ViewPagerResourceId);
fragmentManager = fragment.ChildFragmentManager;
}
// check for a ViewPager inside an Activity
if (attribute.ActivityHostViewModelType != null)
{
var currentActivityViewModelType = GetCurrentActivityViewModelType();
// if the host Activity is not the top-most Activity, then show it before proceeding, and return false for now
if (attribute.ActivityHostViewModelType != currentActivityViewModelType)
{
PendingRequest = request;
ShowHostActivity(attribute);
return Task.FromResult(false);
}
if (CurrentActivity.IsActivityAlive())
viewPager = CurrentActivity!.FindViewById<ViewPager>(attribute.ViewPagerResourceId);
fragmentManager = CurrentFragmentManager;
}
// no more cases to check. Just throw if ViewPager wasn't found
if (viewPager == null)
throw new MvxException("ViewPager not found");
var tag = attribute.Tag ?? attribute.ViewType.FragmentJavaName();
var fragmentInfo = new MvxViewPagerFragmentInfo(attribute.Title, tag, attribute.ViewType, request);
if (viewPager.Adapter is MvxCachingFragmentStatePagerAdapter adapter)
{
adapter.FragmentsInfo.Add(fragmentInfo);
adapter.NotifyDataSetChanged();
}
else
{
viewPager.Adapter = new MvxCachingFragmentStatePagerAdapter(
CurrentActivity,
fragmentManager,
new List<MvxViewPagerFragmentInfo>
{
fragmentInfo
}
);
}
return Task.FromResult(true);
}
protected virtual async Task<bool> ShowTabLayout(
Type view,
MvxTabLayoutPresentationAttribute attribute,
MvxViewModelRequest request)
{
ValidateArguments(view, attribute, request);
var showViewPagerFragment = await ShowViewPagerFragment(view, attribute, request).ConfigureAwait(true);
if (!showViewPagerFragment)
return false;
ViewPager? viewPager = null;
TabLayout? tabLayout = null;
// check for a ViewPager inside a Fragment
if (attribute.FragmentHostViewType != null)
{
var fragment = GetFragmentByViewType(attribute.FragmentHostViewType);
viewPager = fragment?.View.FindViewById<ViewPager>(attribute.ViewPagerResourceId);
tabLayout = fragment?.View.FindViewById<TabLayout>(attribute.TabLayoutResourceId);
}
// check for a ViewPager inside an Activity
if (CurrentActivity.IsActivityAlive() && attribute?.ActivityHostViewModelType != null)
{
viewPager = CurrentActivity?.FindViewById<ViewPager>(attribute.ViewPagerResourceId);
tabLayout = CurrentActivity?.FindViewById<TabLayout>(attribute.TabLayoutResourceId);
}
if (viewPager == null || tabLayout == null)
throw new MvxException("ViewPager or TabLayout not found");
tabLayout.SetupWithViewPager(viewPager);
return true;
}
#endregion
#region Close implementations
protected virtual Task<bool> CloseActivity(IMvxViewModel viewModel, MvxActivityPresentationAttribute? attribute)
{
var currentView = CurrentActivity as IMvxView;
if (currentView == null)
{
_logger.Value?.Warn("Ignoring close for viewmodel - rootframe has no current page");
return Task.FromResult(false);
}
if (currentView.ViewModel != viewModel)
{
_logger.Value?.Warn("Ignoring close for viewmodel - rootframe's current page is not the view for the requested viewmodel");
return Task.FromResult(false);
}
// don't kill the dead
if (CurrentActivity.IsActivityAlive())
CurrentActivity!.Finish();
return Task.FromResult(true);
}
protected virtual Task<bool> CloseFragmentDialog(
IMvxViewModel viewModel, MvxDialogFragmentPresentationAttribute attribute)
{
ValidateArguments(attribute);
string tag = attribute.ViewType.FragmentJavaName();
var toClose = CurrentFragmentManager?.FindFragmentByTag(tag);
if (toClose is DialogFragment dialog)
{
dialog.DismissAllowingStateLoss();
return Task.FromResult(true);
}
return Task.FromResult(false);
}
protected virtual bool CloseFragments()
{
try
{
CurrentFragmentManager?.PopBackStackImmediate();
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (System.Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
_logger.Value?.Trace("Cannot close any fragments", ex);
}
return true;
}
protected virtual Task<bool> CloseFragment(
IMvxViewModel viewModel, MvxFragmentPresentationAttribute attribute)
{
ValidateArguments(attribute);
// try to close nested fragment first
if (attribute.FragmentHostViewType != null)
{
var fragmentHost = GetFragmentByViewType(attribute.FragmentHostViewType);
if (fragmentHost != null
&& TryPerformCloseFragmentTransaction(fragmentHost.ChildFragmentManager, attribute))
return Task.FromResult(true);
}
// Close fragment. If it isn't successful, then close the current Activity
if (CurrentFragmentManager != null && TryPerformCloseFragmentTransaction(CurrentFragmentManager, attribute))
{
return Task.FromResult(true);
}
if (CurrentActivity.IsActivityAlive())
{
CurrentActivity!.Finish();
return Task.FromResult(true);
}
return Task.FromResult(false);
}
protected virtual bool TryPerformCloseFragmentTransaction(
FragmentManager fragmentManager,
MvxFragmentPresentationAttribute fragmentAttribute)
{
ValidateArguments(fragmentAttribute);
if (fragmentManager == null)
throw new ArgumentNullException(nameof(fragmentManager));
try
{
var fragmentName = fragmentAttribute.ViewType.FragmentJavaName();
if (fragmentManager.BackStackEntryCount > 0)
{
PopOnBackstackEntries(fragmentName, fragmentManager, fragmentAttribute);
return true;
}
Fragment fragmentToPop = fragmentManager.FindFragmentByTag(fragmentName);
if (fragmentToPop != null)
{
PopFragment(fragmentManager, fragmentAttribute, fragmentToPop);
return true;
}
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (System.Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
_logger.Value?.Error("Cannot close fragment transaction", ex);
return false;
}
return false;
}
private void PopFragment(FragmentManager fragmentManager, MvxFragmentPresentationAttribute fragmentAttribute,
Fragment fragmentToPop)
{
var ft = fragmentManager.BeginTransaction();
if (!fragmentAttribute.EnterAnimation.Equals(int.MinValue) &&
!fragmentAttribute.ExitAnimation.Equals(int.MinValue))
{
if (!fragmentAttribute.PopEnterAnimation.Equals(int.MinValue) &&
!fragmentAttribute.PopExitAnimation.Equals(int.MinValue))
{
ft.SetCustomAnimations(
fragmentAttribute.EnterAnimation,
fragmentAttribute.ExitAnimation,
fragmentAttribute.PopEnterAnimation,
fragmentAttribute.PopExitAnimation);
}
else
{
ft.SetCustomAnimations(
fragmentAttribute.EnterAnimation,
fragmentAttribute.ExitAnimation);
}
}
if (fragmentAttribute.TransitionStyle != int.MinValue)
ft.SetTransitionStyle(fragmentAttribute.TransitionStyle);
ft.Remove(fragmentToPop);
ft.CommitAllowingStateLoss();
OnFragmentPopped(ft, fragmentToPop, fragmentAttribute);
}
private void PopOnBackstackEntries(
string fragmentName, FragmentManager fragmentManager, MvxFragmentPresentationAttribute fragmentAttribute)
{
var popBackStackFragmentName =
string.IsNullOrEmpty(fragmentAttribute.PopBackStackImmediateName?.Trim())
? fragmentName
: fragmentAttribute.PopBackStackImmediateName;
fragmentManager.PopBackStackImmediate(
popBackStackFragmentName,
(int) fragmentAttribute.PopBackStackImmediateFlag.ToNativePopBackStackFlags());
OnFragmentPopped(null, null, fragmentAttribute);
}
protected virtual Task<bool> CloseViewPagerFragment(
IMvxViewModel? viewModel,
MvxViewPagerFragmentPresentationAttribute attribute)
{
ValidateArguments(attribute);
ViewPager? viewPager = null;
FragmentManager? fragmentManager;
if (attribute.FragmentHostViewType != null)
{
var fragment = GetFragmentByViewType(attribute.FragmentHostViewType);
if (fragment == null)
throw new MvxException("Fragment not found", attribute.FragmentHostViewType.Name);
viewPager = fragment.View.FindViewById<ViewPager>(attribute.ViewPagerResourceId);
fragmentManager = fragment.ChildFragmentManager;
}
else
{
if (CurrentActivity.IsActivityAlive())
viewPager = CurrentActivity!.FindViewById<ViewPager>(attribute.ViewPagerResourceId);
fragmentManager = CurrentFragmentManager;
}