summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.Android/Platform.cs
blob: ca0b9708a1dd08c4328981fe181c16ce95a802c8 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Support.V4.App;
using Android.Util;
using Android.Views;
using Android.Widget;
using Xamarin.Forms.Platform.Android.AppCompat;
using FragmentManager = Android.Support.V4.App.FragmentManager;
using Xamarin.Forms.Internals;

namespace Xamarin.Forms.Platform.Android
{
	public class Platform : BindableObject, IPlatform, INavigation, IDisposable, IPlatformLayout
	{
		internal const string CloseContextActionsSignalName = "Xamarin.CloseContextActions";

		internal static readonly BindableProperty RendererProperty = BindableProperty.CreateAttached("Renderer", typeof(IVisualElementRenderer), typeof(Platform), default(IVisualElementRenderer),
			propertyChanged: (bindable, oldvalue, newvalue) =>
			{
				var view = bindable as VisualElement;
				if (view != null)
					view.IsPlatformEnabled = newvalue != null;
			});

		internal static readonly BindableProperty PageContextProperty = BindableProperty.CreateAttached("PageContext", typeof(Context), typeof(Platform), null);

		IMasterDetailPageController MasterDetailPageController => CurrentMasterDetailPage as IMasterDetailPageController;

		readonly Context _context;

		readonly PlatformRenderer _renderer;
		readonly ToolbarTracker _toolbarTracker = new ToolbarTracker();

		NavigationPage _currentNavigationPage;

		TabbedPage _currentTabbedPage;

		Color _defaultActionBarTitleTextColor;

		bool _disposed;

		bool _ignoreAndroidSelection;

		Page _navigationPageCurrentPage;
		NavigationModel _navModel = new NavigationModel();

		internal Platform(Context context)
		{
			_context = context;

			_defaultActionBarTitleTextColor = SetDefaultActionBarTitleTextColor();

			_renderer = new PlatformRenderer(context, this);

			FormsApplicationActivity.BackPressed += HandleBackPressed;

			_toolbarTracker.CollectionChanged += ToolbarTrackerOnCollectionChanged;
		}

		#region IPlatform implementation

		internal Page Page { get; private set; }

		#endregion

		IPageController CurrentPageController => _navModel.CurrentPage as IPageController;

		ActionBar ActionBar
		{
			get { return ((Activity)_context).ActionBar; }
		}

		MasterDetailPage CurrentMasterDetailPage { get; set; }

		NavigationPage CurrentNavigationPage
		{
			get { return _currentNavigationPage; }
			set
			{
				if (_currentNavigationPage == value)
					return;

				if (_currentNavigationPage != null)
				{
					_currentNavigationPage.Pushed -= CurrentNavigationPageOnPushed;
					_currentNavigationPage.Popped -= CurrentNavigationPageOnPopped;
					_currentNavigationPage.PoppedToRoot -= CurrentNavigationPageOnPoppedToRoot;
					_currentNavigationPage.PropertyChanged -= CurrentNavigationPageOnPropertyChanged;
				}

				RegisterNavPageCurrent(null);

				_currentNavigationPage = value;

				if (_currentNavigationPage != null)
				{
					_currentNavigationPage.Pushed += CurrentNavigationPageOnPushed;
					_currentNavigationPage.Popped += CurrentNavigationPageOnPopped;
					_currentNavigationPage.PoppedToRoot += CurrentNavigationPageOnPoppedToRoot;
					_currentNavigationPage.PropertyChanged += CurrentNavigationPageOnPropertyChanged;
					RegisterNavPageCurrent(_currentNavigationPage.CurrentPage);
				}

				UpdateActionBarBackgroundColor();
				UpdateActionBarTextColor();
				UpdateActionBarUpImageColor();
				UpdateActionBarTitle();
			}
		}

		TabbedPage CurrentTabbedPage
		{
			get { return _currentTabbedPage; }
			set
			{
				if (_currentTabbedPage == value)
					return;

				if (_currentTabbedPage != null)
				{
					_currentTabbedPage.PagesChanged -= CurrentTabbedPageChildrenChanged;
					_currentTabbedPage.PropertyChanged -= CurrentTabbedPageOnPropertyChanged;

					if (value == null)
						ActionBar.RemoveAllTabs();
				}

				_currentTabbedPage = value;

				if (_currentTabbedPage != null)
				{
					_currentTabbedPage.PagesChanged += CurrentTabbedPageChildrenChanged;
					_currentTabbedPage.PropertyChanged += CurrentTabbedPageOnPropertyChanged;
				}

				UpdateActionBarTitle();

				ActionBar.NavigationMode = value == null ? ActionBarNavigationMode.Standard : ActionBarNavigationMode.Tabs;
				CurrentTabbedPageChildrenChanged(null, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
			}
		}

#pragma warning disable 618 // Eventually we will need to determine how to handle the v7 ActionBarDrawerToggle for AppCompat
		ActionBarDrawerToggle MasterDetailPageToggle { get; set; }
#pragma warning restore 618

		void IDisposable.Dispose()
		{
			if (_disposed)
				return;
			_disposed = true;

			SetPage(null);

			FormsApplicationActivity.BackPressed -= HandleBackPressed;
			_toolbarTracker.CollectionChanged -= ToolbarTrackerOnCollectionChanged;
			_toolbarTracker.Target = null;

			CurrentNavigationPage = null;
			CurrentMasterDetailPage = null;
			CurrentTabbedPage = null;
		}

		void INavigation.InsertPageBefore(Page page, Page before)
		{
			throw new InvalidOperationException("InsertPageBefore is not supported globally on Android, please use a NavigationPage.");
		}

		IReadOnlyList<Page> INavigation.ModalStack => _navModel.Modals.ToList();

		IReadOnlyList<Page> INavigation.NavigationStack => new List<Page>();

		Task<Page> INavigation.PopAsync()
		{
			return ((INavigation)this).PopAsync(true);
		}

		Task<Page> INavigation.PopAsync(bool animated)
		{
			throw new InvalidOperationException("PopAsync is not supported globally on Android, please use a NavigationPage.");
		}

		Task<Page> INavigation.PopModalAsync()
		{
			return ((INavigation)this).PopModalAsync(true);
		}

		Task<Page> INavigation.PopModalAsync(bool animated)
		{
			Page modal = _navModel.PopModal();

			((IPageController)modal).SendDisappearing();
			var source = new TaskCompletionSource<Page>();

			IVisualElementRenderer modalRenderer = GetRenderer(modal);
			if (modalRenderer != null)
			{
				if (animated)
				{
					modalRenderer.ViewGroup.Animate().Alpha(0).ScaleX(0.8f).ScaleY(0.8f).SetDuration(250).SetListener(new GenericAnimatorListener
					{
						OnEnd = a =>
						{
							modalRenderer.ViewGroup.RemoveFromParent();
							modalRenderer.Dispose();
							source.TrySetResult(modal);
							CurrentPageController?.SendAppearing();
						}
					});
				}
				else
				{
					modalRenderer.ViewGroup.RemoveFromParent();
					modalRenderer.Dispose();
					source.TrySetResult(modal);
					CurrentPageController?.SendAppearing();
				}
			}

			_toolbarTracker.Target = _navModel.Roots.Last();
			UpdateActionBar();

			return source.Task;
		}

		Task INavigation.PopToRootAsync()
		{
			return ((INavigation)this).PopToRootAsync(true);
		}

		Task INavigation.PopToRootAsync(bool animated)
		{
			throw new InvalidOperationException("PopToRootAsync is not supported globally on Android, please use a NavigationPage.");
		}

		Task INavigation.PushAsync(Page root)
		{
			return ((INavigation)this).PushAsync(root, true);
		}

		Task INavigation.PushAsync(Page root, bool animated)
		{
			throw new InvalidOperationException("PushAsync is not supported globally on Android, please use a NavigationPage.");
		}

		Task INavigation.PushModalAsync(Page modal)
		{
			return ((INavigation)this).PushModalAsync(modal, true);
		}

		async Task INavigation.PushModalAsync(Page modal, bool animated)
		{
			CurrentPageController?.SendDisappearing();

			_navModel.PushModal(modal);

			modal.Platform = this;

			await PresentModal(modal, animated);

			// Verify that the modal is still on the stack
			if (_navModel.CurrentPage == modal)
				((IPageController)modal).SendAppearing();

			_toolbarTracker.Target = _navModel.Roots.Last();

			UpdateActionBar();
		}

		void INavigation.RemovePage(Page page)
		{
			throw new InvalidOperationException("RemovePage is not supported globally on Android, please use a NavigationPage.");
		}

		public static IVisualElementRenderer CreateRenderer(VisualElement element)
		{
			UpdateGlobalContext(element);

			IVisualElementRenderer renderer = Registrar.Registered.GetHandler<IVisualElementRenderer>(element.GetType()) ?? new DefaultRenderer();
			renderer.SetElement(element);

			return renderer;
		}

		public static IVisualElementRenderer GetRenderer(VisualElement bindable)
		{
			return (IVisualElementRenderer)bindable.GetValue(RendererProperty);
		}

		public static void SetRenderer(VisualElement bindable, IVisualElementRenderer value)
		{
			bindable.SetValue(RendererProperty, value);
		}

		public void UpdateActionBarTextColor()
		{
			SetActionBarTextColor();
		}

		protected override void OnBindingContextChanged()
		{
			SetInheritedBindingContext(Page, BindingContext);

			base.OnBindingContextChanged();
		}

		internal static IVisualElementRenderer CreateRenderer(VisualElement element, FragmentManager fragmentManager)
		{
			UpdateGlobalContext(element);

			IVisualElementRenderer renderer = Registrar.Registered.GetHandler<IVisualElementRenderer>(element.GetType()) ?? new DefaultRenderer();

			var managesFragments = renderer as IManageFragments;
			managesFragments?.SetFragmentManager(fragmentManager);

			renderer.SetElement(element);

			return renderer;
		}

		internal static Context GetPageContext(BindableObject bindable)
		{
			return (Context)bindable.GetValue(PageContextProperty);
		}

		internal ViewGroup GetViewGroup()
		{
			return _renderer;
		}

		internal void PrepareMenu(IMenu menu)
		{
			foreach (ToolbarItem item in _toolbarTracker.ToolbarItems)
				item.PropertyChanged -= HandleToolbarItemPropertyChanged;
			menu.Clear();

			if (!ShouldShowActionBarTitleArea())
				return;

			foreach (ToolbarItem item in _toolbarTracker.ToolbarItems)
			{
				IMenuItemController controller = item;
				item.PropertyChanged += HandleToolbarItemPropertyChanged;
				if (item.Order == ToolbarItemOrder.Secondary)
				{
					IMenuItem menuItem = menu.Add(item.Text);
					menuItem.SetEnabled(controller.IsEnabled);
					menuItem.SetOnMenuItemClickListener(new GenericMenuClickListener(controller.Activate));
				}
				else
				{
					IMenuItem menuItem = menu.Add(item.Text);
					if (!string.IsNullOrEmpty(item.Icon))
					{
						var iconBitmap = new BitmapDrawable(_context.Resources, ResourceManager.GetBitmap(_context.Resources, item.Icon));
						if (iconBitmap != null && iconBitmap.Bitmap != null)
							menuItem.SetIcon(iconBitmap);
					}
					menuItem.SetEnabled(controller.IsEnabled);
					menuItem.SetShowAsAction(ShowAsAction.Always);
					menuItem.SetOnMenuItemClickListener(new GenericMenuClickListener(controller.Activate));
				}
			}
		}

		internal async void SendHomeClicked()
		{
			if (UpButtonShouldNavigate())
			{
				if (NavAnimationInProgress)
					return;
				NavAnimationInProgress = true;
				await CurrentNavigationPage.PopAsync();
				NavAnimationInProgress = false;
			}
			else if (CurrentMasterDetailPage != null)
			{
				if (MasterDetailPageController.ShouldShowSplitMode && CurrentMasterDetailPage.IsPresented)
					return;
				CurrentMasterDetailPage.IsPresented = !CurrentMasterDetailPage.IsPresented;
			}
		}

		internal void SetPage(Page newRoot)
		{
			var layout = false;
			if (Page != null)
			{
				_renderer.RemoveAllViews();

				foreach (IVisualElementRenderer rootRenderer in _navModel.Roots.Select(GetRenderer))
					rootRenderer.Dispose();
				_navModel = new NavigationModel();

				layout = true;
			}

			if (newRoot == null)
				return;

			_navModel.Push(newRoot, null);

			Page = newRoot;
			Page.Platform = this;
			AddChild(Page, layout);

			Application.Current.NavigationProxy.Inner = this;

			_toolbarTracker.Target = newRoot;

			UpdateActionBar();
		}

		internal static void SetPageContext(BindableObject bindable, Context context)
		{
			bindable.SetValue(PageContextProperty, context);
		}

		internal void UpdateActionBar()
		{
			if (ActionBar == null) //Fullscreen theme doesn't have action bar
			{
				return;
			}
			List<Page> relevantAncestors = AncestorPagesOfPage(_navModel.CurrentPage);

			IEnumerable<NavigationPage> navPages = relevantAncestors.OfType<NavigationPage>();
			if (navPages.Count() > 1)
				throw new Exception("Android only allows one navigation page on screen at a time");
			NavigationPage navPage = navPages.FirstOrDefault();

			IEnumerable<TabbedPage> tabbedPages = relevantAncestors.OfType<TabbedPage>();
			if (tabbedPages.Count() > 1)
				throw new Exception("Android only allows one tabbed page on screen at a time");
			TabbedPage tabbedPage = tabbedPages.FirstOrDefault();

			CurrentMasterDetailPage = relevantAncestors.OfType<MasterDetailPage>().FirstOrDefault();
			CurrentNavigationPage = navPage;
			CurrentTabbedPage = tabbedPage;

			if (navPage != null && navPage.CurrentPage == null)
			{
				throw new InvalidOperationException("NavigationPage must have a root Page before being used. Either call PushAsync with a valid Page, or pass a Page to the constructor before usage.");
			}

			UpdateActionBarTitle();

			if (ShouldShowActionBarTitleArea() || tabbedPage != null)
				ShowActionBar();
			else
				HideActionBar();
			UpdateMasterDetailToggle();
		}

		internal void UpdateActionBarBackgroundColor()
		{
			if (!((Activity)_context).ActionBar.IsShowing)
				return;
			Color colorToUse = Color.Default;
			if (CurrentNavigationPage != null)
			{
#pragma warning disable 618 // Make sure Tint still works 
				if (CurrentNavigationPage.Tint != Color.Default)
					colorToUse = CurrentNavigationPage.Tint;
#pragma warning restore 618
				else if (CurrentNavigationPage.BarBackgroundColor != Color.Default)
					colorToUse = CurrentNavigationPage.BarBackgroundColor;
			}
			using (Drawable drawable = colorToUse == Color.Default ? GetActionBarBackgroundDrawable() : new ColorDrawable(colorToUse.ToAndroid()))
				((Activity)_context).ActionBar.SetBackgroundDrawable(drawable);
		}

		internal void UpdateMasterDetailToggle(bool update = false)
		{
			if (CurrentMasterDetailPage == null)
			{
				if (MasterDetailPageToggle == null)
					return;
				// clear out the icon
				ClearMasterDetailToggle();
				return;
			}
			if (!CurrentMasterDetailPage.ShouldShowToolbarButton() || string.IsNullOrEmpty(CurrentMasterDetailPage.Master.Icon) ||
				(MasterDetailPageController.ShouldShowSplitMode && CurrentMasterDetailPage.IsPresented))
			{
				//clear out existing icon;
				ClearMasterDetailToggle();
				return;
			}

			if (MasterDetailPageToggle == null || update)
			{
				ClearMasterDetailToggle();
				GetNewMasterDetailToggle();
			}

			bool state;
			if (CurrentNavigationPage == null)
				state = true;
			else
				state = !UpButtonShouldNavigate();
			if (state == MasterDetailPageToggle.DrawerIndicatorEnabled)
				return;
			MasterDetailPageToggle.DrawerIndicatorEnabled = state;
			MasterDetailPageToggle.SyncState();
		}

		internal void UpdateNavigationTitleBar()
		{
			UpdateActionBarTitle();
			UpdateActionBar();
			UpdateActionBarUpImageColor();
		}

		void AddChild(VisualElement view, bool layout = false)
		{
			if (GetRenderer(view) != null)
				return;

			SetPageContext(view, _context);
			IVisualElementRenderer renderView = CreateRenderer(view);
			SetRenderer(view, renderView);

			if (layout)
				view.Layout(new Rectangle(0, 0, _context.FromPixels(_renderer.Width), _context.FromPixels(_renderer.Height)));

			_renderer.AddView(renderView.ViewGroup);
		}

#pragma warning disable 618 // This may need to be updated to work with TabLayout/AppCompat
		ActionBar.Tab AddTab(Page page, int index)
#pragma warning restore 618
		{
			ActionBar actionBar = ((Activity)_context).ActionBar;
			TabbedPage currentTabs = CurrentTabbedPage;

			var atab = actionBar.NewTab();
			atab.SetText(page.Title);
			atab.TabSelected += (sender, e) =>
			{
				if (!_ignoreAndroidSelection)
					currentTabs.CurrentPage = page;
			};
			actionBar.AddTab(atab, index);

			page.PropertyChanged += PagePropertyChanged;
			return atab;
		}

		List<Page> AncestorPagesOfPage(Page root)
		{
			var result = new List<Page>();
			if (root == null)
				return result;

			if (root is IPageContainer<Page>)
			{
				var navPage = (IPageContainer<Page>)root;
				result.AddRange(AncestorPagesOfPage(navPage.CurrentPage));
			}
			else if (root is MasterDetailPage)
				result.AddRange(AncestorPagesOfPage(((MasterDetailPage)root).Detail));
			else
			{
				foreach (Page page in ((IPageController)root).InternalChildren.OfType<Page>())
					result.AddRange(AncestorPagesOfPage(page));
			}

			result.Add(root);
			return result;
		}

		void ClearMasterDetailToggle()
		{
			if (MasterDetailPageToggle == null)
				return;

			MasterDetailPageToggle.DrawerIndicatorEnabled = false;
			MasterDetailPageToggle.SyncState();
			MasterDetailPageToggle.Dispose();
			MasterDetailPageToggle = null;
		}

		void CurrentNavigationPageOnPopped(object sender, NavigationEventArgs eventArg)
		{
			UpdateNavigationTitleBar();
		}

		void CurrentNavigationPageOnPoppedToRoot(object sender, EventArgs eventArgs)
		{
			UpdateNavigationTitleBar();
		}

		void CurrentNavigationPageOnPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
#pragma warning disable 618 // Make sure Tint still works
			if (e.PropertyName == NavigationPage.TintProperty.PropertyName)
#pragma warning restore 618
				UpdateActionBarBackgroundColor();
			else if (e.PropertyName == NavigationPage.BarBackgroundColorProperty.PropertyName)
				UpdateActionBarBackgroundColor();
			else if (e.PropertyName == NavigationPage.BarTextColorProperty.PropertyName)
			{
				UpdateActionBarTextColor();
				UpdateActionBarUpImageColor();
			}
			else if (e.PropertyName == NavigationPage.CurrentPageProperty.PropertyName)
				RegisterNavPageCurrent(CurrentNavigationPage.CurrentPage);
		}

		void CurrentNavigationPageOnPushed(object sender, NavigationEventArgs eventArg)
		{
			UpdateNavigationTitleBar();
		}

		void CurrentTabbedPageChildrenChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (CurrentTabbedPage == null)
				return;

			_ignoreAndroidSelection = true;

			e.Apply((o, index, create) => AddTab((Page)o, index), (o, index) => RemoveTab((Page)o, index), Reset);

			if (CurrentTabbedPage.CurrentPage != null)
			{
				Page page = CurrentTabbedPage.CurrentPage;
				int index = TabbedPage.GetIndex(page);
				if (index >= 0 && index < CurrentTabbedPage.Children.Count)
					ActionBar.GetTabAt(index).Select();
			}

			_ignoreAndroidSelection = false;
		}

		void CurrentTabbedPageOnPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName != "CurrentPage")
				return;

			UpdateActionBar();

			// If we switch tabs while pushing a new page, UpdateActionBar() can set currentTabbedPage to null
			if (_currentTabbedPage == null)
				return;

			NavAnimationInProgress = true;

			Page page = _currentTabbedPage.CurrentPage;
			if (page == null)
			{
				ActionBar.SelectTab(null);
				NavAnimationInProgress = false;
				return;
			}

			int index = TabbedPage.GetIndex(page);
			if (ActionBar.SelectedNavigationIndex == index || index >= ActionBar.NavigationItemCount)
			{
				NavAnimationInProgress = false;
				return;
			}

			ActionBar.SelectTab(ActionBar.GetTabAt(index));

			NavAnimationInProgress = false;
		}

		Drawable GetActionBarBackgroundDrawable()
		{
			int[] backgroundDataArray = { global::Android.Resource.Attribute.Background };

			using (var outVal = new TypedValue())
			{
				_context.Theme.ResolveAttribute(global::Android.Resource.Attribute.ActionBarStyle, outVal, true);
				TypedArray actionBarStyle = _context.Theme.ObtainStyledAttributes(outVal.ResourceId, backgroundDataArray);

				Drawable result = actionBarStyle.GetDrawable(0);
				actionBarStyle.Recycle();
				return result;
			}
		}

		void GetNewMasterDetailToggle()
		{
			int icon = ResourceManager.GetDrawableByName(CurrentMasterDetailPage.Master.Icon);
			var drawer = GetRenderer(CurrentMasterDetailPage) as MasterDetailRenderer;
			if (drawer == null)
				return;

#pragma warning disable 618 // Eventually we will need to determine how to handle the v7 ActionBarDrawerToggle for AppCompat
			MasterDetailPageToggle = new ActionBarDrawerToggle(_context as Activity, drawer, icon, 0, 0);
#pragma warning restore 618

			MasterDetailPageToggle.SyncState();
		}

		bool HandleBackPressed(object sender, EventArgs e)
		{
			if (NavAnimationInProgress)
				return true;

			Page root = _navModel.Roots.Last();
			bool handled = root.SendBackButtonPressed();

			return handled;
		}

		void HandleToolbarItemPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == MenuItem.IsEnabledProperty.PropertyName)
				(_context as Activity).InvalidateOptionsMenu();
			else if (e.PropertyName == MenuItem.TextProperty.PropertyName)
				(_context as Activity).InvalidateOptionsMenu();
			else if (e.PropertyName == MenuItem.IconProperty.PropertyName)
				(_context as Activity).InvalidateOptionsMenu();
		}

		void HideActionBar()
		{
			ReloadToolbarItems();
			UpdateActionBarHomeAsUp(ActionBar);
			ActionBar.Hide();
		}

		void NavigationPageCurrentPageOnPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == NavigationPage.HasNavigationBarProperty.PropertyName)
				UpdateActionBar();
			else if (e.PropertyName == Page.TitleProperty.PropertyName)
				UpdateActionBarTitle();
		}

		void PagePropertyChanged(object sender, PropertyChangedEventArgs args)
		{
			if (args.PropertyName == Page.TitleProperty.PropertyName)
			{
				ActionBar actionBar = ((Activity)_context).ActionBar;
				TabbedPage currentTabs = CurrentTabbedPage;

				if (currentTabs == null || actionBar.TabCount == 0)
					return;

				var page = sender as Page;
				var atab = actionBar.GetTabAt(currentTabs.Children.IndexOf(page));
				atab.SetText(page.Title);
			}
		}

		Task PresentModal(Page modal, bool animated)
		{
			IVisualElementRenderer modalRenderer = GetRenderer(modal);
			if (modalRenderer == null)
			{
				SetPageContext(modal, _context);
				modalRenderer = CreateRenderer(modal);
				SetRenderer(modal, modalRenderer);

				if (modal.BackgroundColor == Color.Default && modal.BackgroundImage == null)
					modalRenderer.ViewGroup.SetWindowBackground();
			}
			modalRenderer.Element.Layout(new Rectangle(0, 0, _context.FromPixels(_renderer.Width), _context.FromPixels(_renderer.Height)));
			_renderer.AddView(modalRenderer.ViewGroup);

			var source = new TaskCompletionSource<bool>();
			NavAnimationInProgress = true;
			if (animated)
			{
				modalRenderer.ViewGroup.Alpha = 0;
				modalRenderer.ViewGroup.ScaleX = 0.8f;
				modalRenderer.ViewGroup.ScaleY = 0.8f;
				modalRenderer.ViewGroup.Animate().Alpha(1).ScaleX(1).ScaleY(1).SetDuration(250).SetListener(new GenericAnimatorListener
				{
					OnEnd = a =>
					{
						source.TrySetResult(false);
						NavAnimationInProgress = false;
					},
					OnCancel = a =>
					{
						source.TrySetResult(true);
						NavAnimationInProgress = false;
					}
				});
			}
			else
			{
				NavAnimationInProgress = false;
				source.TrySetResult(true);
			}

			return source.Task;
		}

		void RegisterNavPageCurrent(Page page)
		{
			if (_navigationPageCurrentPage != null)
				_navigationPageCurrentPage.PropertyChanged -= NavigationPageCurrentPageOnPropertyChanged;

			_navigationPageCurrentPage = page;

			if (_navigationPageCurrentPage != null)
				_navigationPageCurrentPage.PropertyChanged += NavigationPageCurrentPageOnPropertyChanged;
		}

		void ReloadToolbarItems()
		{
			var activity = (Activity)_context;
			activity.InvalidateOptionsMenu();
		}

		void RemoveTab(Page page, int index)
		{
			ActionBar actionBar = ((Activity)_context).ActionBar;
			page.PropertyChanged -= PagePropertyChanged;
			actionBar.RemoveTabAt(index);
		}

		void Reset()
		{
			ActionBar.RemoveAllTabs();

			if (CurrentTabbedPage == null)
				return;

			var i = 0;
			foreach (Page tab in CurrentTabbedPage.Children.OfType<Page>())
			{
				var realTab = AddTab(tab, i++);
				if (tab == CurrentTabbedPage.CurrentPage)
					realTab.Select();
			}
		}

		void SetActionBarTextColor()
		{
			Color navigationBarTextColor = CurrentNavigationPage == null ? Color.Default : CurrentNavigationPage.BarTextColor;
			TextView actionBarTitleTextView = null;

			if(Forms.IsLollipopOrNewer)
			{
				int actionbarId = _context.Resources.GetIdentifier("action_bar", "id", "android");
				if(actionbarId > 0)
				{
					var toolbar = (Toolbar)((Activity)_context).FindViewById(actionbarId);
					actionBarTitleTextView = (TextView)toolbar.GetChildAt(0);
				}
			}
			else
			{
				int actionBarTitleId = _context.Resources.GetIdentifier("action_bar_title", "id", "android");
				if (actionBarTitleId > 0)
					actionBarTitleTextView = ((Activity)_context).FindViewById<TextView>(actionBarTitleId);
			}

			if (actionBarTitleTextView != null && navigationBarTextColor != Color.Default)
				actionBarTitleTextView.SetTextColor(navigationBarTextColor.ToAndroid());
			else if (actionBarTitleTextView != null && navigationBarTextColor == Color.Default)
				actionBarTitleTextView.SetTextColor(_defaultActionBarTitleTextColor.ToAndroid());
		}

		Color SetDefaultActionBarTitleTextColor()
		{
			var defaultTitleTextColor = new Color();

			TextView actionBarTitleTextView = null;

			int actionBarTitleId = _context.Resources.GetIdentifier("action_bar_title", "id", "android");
			if (actionBarTitleId > 0)
				actionBarTitleTextView = ((Activity)_context).FindViewById<TextView>(actionBarTitleId);

			if (actionBarTitleTextView != null)
			{
				ColorStateList defaultTitleColorList = actionBarTitleTextView.TextColors;
				string defaultColorHex = defaultTitleColorList.DefaultColor.ToString("X");
				defaultTitleTextColor = Color.FromHex(defaultColorHex);
			}

			return defaultTitleTextColor;
		}

		bool ShouldShowActionBarTitleArea()
		{
			if (Forms.TitleBarVisibility == AndroidTitleBarVisibility.Never)
				return false;

			bool hasMasterDetailPage = CurrentMasterDetailPage != null;
			bool navigated = CurrentNavigationPage != null && ((INavigationPageController)CurrentNavigationPage).StackDepth > 1;
			bool navigationPageHasNavigationBar = CurrentNavigationPage != null && NavigationPage.GetHasNavigationBar(CurrentNavigationPage.CurrentPage);
			return navigationPageHasNavigationBar || (hasMasterDetailPage && !navigated);
		}

		bool ShouldUpdateActionBarUpColor()
		{
			bool hasMasterDetailPage = CurrentMasterDetailPage != null;
			bool navigated = CurrentNavigationPage != null && ((INavigationPageController)CurrentNavigationPage).StackDepth > 1;
			return (hasMasterDetailPage && navigated) || !hasMasterDetailPage;
		}

		void ShowActionBar()
		{
			ReloadToolbarItems();
			UpdateActionBarHomeAsUp(ActionBar);
			ActionBar.Show();
			UpdateActionBarBackgroundColor();
			UpdateActionBarTextColor();
		}

		void ToolbarTrackerOnCollectionChanged(object sender, EventArgs eventArgs)
		{
			ReloadToolbarItems();
		}

		bool UpButtonShouldNavigate()
		{
			if (CurrentNavigationPage == null)
				return false;

			bool pagePushed = ((INavigationPageController)CurrentNavigationPage).StackDepth > 1;
			bool pushedPageHasBackButton = NavigationPage.GetHasBackButton(CurrentNavigationPage.CurrentPage);

			return pagePushed && pushedPageHasBackButton;
		}

		void UpdateActionBarHomeAsUp(ActionBar actionBar)
		{
			bool showHomeAsUp = ShouldShowActionBarTitleArea() && (CurrentMasterDetailPage != null || UpButtonShouldNavigate());
			actionBar.SetDisplayHomeAsUpEnabled(showHomeAsUp);
		}

		void UpdateActionBarTitle()
		{
			Page view = null;
			if (CurrentNavigationPage != null)
				view = CurrentNavigationPage.CurrentPage;
			else if (CurrentTabbedPage != null)
				view = CurrentTabbedPage.CurrentPage;

			if (view == null)
				return;

			ActionBar actionBar = ((Activity)_context).ActionBar;

			var useLogo = false;
			var showHome = false;
			var showTitle = false;

			if (ShouldShowActionBarTitleArea())
			{
				actionBar.Title = view.Title;
				FileImageSource titleIcon = NavigationPage.GetTitleIcon(view);
				if (!string.IsNullOrWhiteSpace(titleIcon))
				{
					var iconBitmap = new BitmapDrawable(_context.Resources, ResourceManager.GetBitmap(_context.Resources, titleIcon));
					if (iconBitmap != null && iconBitmap.Bitmap != null)
						actionBar.SetLogo(iconBitmap);

					useLogo = true;
					showHome = true;
					showTitle = true;
				}
				else
				{
					showHome = true;
					showTitle = true;
				}
			}

			ActionBarDisplayOptions options = 0;
			if (useLogo)
				options = options | ActionBarDisplayOptions.UseLogo;
			if (showHome)
				options = options | ActionBarDisplayOptions.ShowHome;
			if (showTitle)
				options = options | ActionBarDisplayOptions.ShowTitle;
			actionBar.SetDisplayOptions(options, ActionBarDisplayOptions.UseLogo | ActionBarDisplayOptions.ShowTitle | ActionBarDisplayOptions.ShowHome);

			UpdateActionBarHomeAsUp(actionBar);
		}

		void UpdateActionBarUpImageColor()
		{
			Color navigationBarTextColor = CurrentNavigationPage == null ? Color.Default : CurrentNavigationPage.BarTextColor;
			ImageView actionBarUpImageView = null;

			int actionBarUpId = _context.Resources.GetIdentifier("up", "id", "android");
			if (actionBarUpId > 0)
				actionBarUpImageView = ((Activity)_context).FindViewById<ImageView>(actionBarUpId);

			if (actionBarUpImageView != null && navigationBarTextColor != Color.Default)
			{
				if (ShouldUpdateActionBarUpColor())
					actionBarUpImageView.SetColorFilter(navigationBarTextColor.ToAndroid(), PorterDuff.Mode.SrcIn);
				else
					actionBarUpImageView.SetColorFilter(null);
			}
			else if (actionBarUpImageView != null && navigationBarTextColor == Color.Default)
				actionBarUpImageView.SetColorFilter(null);
		}

		static void UpdateGlobalContext(VisualElement view)
		{
			Element parent = view;
			while (!Application.IsApplicationOrNull(parent.RealParent))
				parent = parent.RealParent;

			var rootPage = parent as Page;
			if (rootPage != null)
			{
				Context context = GetPageContext(rootPage);
				if (context != null)
					Forms.Context = context;
			}
		}

		internal class DefaultRenderer : VisualElementRenderer<View>
		{
		}

		#region IPlatformEngine implementation

		void IPlatformLayout.OnLayout(bool changed, int l, int t, int r, int b)
		{
			if (changed)
			{
				// ActionBar title text color resets on rotation, make sure to update
				UpdateActionBarTextColor();
				foreach (Page modal in _navModel.Roots.ToList())
					modal.Layout(new Rectangle(0, 0, _context.FromPixels(r - l), _context.FromPixels(b - t)));
			}

			foreach (IVisualElementRenderer view in _navModel.Roots.Select(GetRenderer))
				view?.UpdateLayout();
		}

		SizeRequest IPlatform.GetNativeSize(VisualElement view, double widthConstraint, double heightConstraint)
		{
			Performance.Start();

			// FIXME: potential crash
			IVisualElementRenderer viewRenderer = GetRenderer(view);

			// negative numbers have special meanings to android they don't to us
			widthConstraint = widthConstraint <= -1 ? double.PositiveInfinity : _context.ToPixels(widthConstraint);
			heightConstraint = heightConstraint <= -1 ? double.PositiveInfinity : _context.ToPixels(heightConstraint);

			int width = !double.IsPositiveInfinity(widthConstraint)
							? MeasureSpecFactory.MakeMeasureSpec((int)widthConstraint, MeasureSpecMode.AtMost)
							: MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified);

			int height = !double.IsPositiveInfinity(heightConstraint)
							 ? MeasureSpecFactory.MakeMeasureSpec((int)heightConstraint, MeasureSpecMode.AtMost)
							 : MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified);

			SizeRequest rawResult = viewRenderer.GetDesiredSize(width, height);
			if (rawResult.Minimum == Size.Zero)
				rawResult.Minimum = rawResult.Request;
			var result = new SizeRequest(new Size(_context.FromPixels(rawResult.Request.Width), _context.FromPixels(rawResult.Request.Height)),
				new Size(_context.FromPixels(rawResult.Minimum.Width), _context.FromPixels(rawResult.Minimum.Height)));

			Performance.Stop();
			return result;
		}

		bool _navAnimationInProgress;

		internal bool NavAnimationInProgress
		{
			get { return _navAnimationInProgress; }
			set
			{
				if (_navAnimationInProgress == value)
					return;
				_navAnimationInProgress = value;
				if (value)
					MessagingCenter.Send(this, CloseContextActionsSignalName);
			}
		}

		#endregion
	}
}