1
0

AvaloniaMainActivity.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using Android.App;
  3. using Android.Content;
  4. using Android.OS;
  5. using Android.Runtime;
  6. using Android.Views;
  7. using AndroidX.AppCompat.App;
  8. namespace Avalonia.Android
  9. {
  10. public abstract class AvaloniaMainActivity : AppCompatActivity, IActivityResultHandler, IActivityNavigationService
  11. {
  12. internal static object ViewContent;
  13. public Action<int, Result, Intent> ActivityResult { get; set; }
  14. internal AvaloniaView View;
  15. private GlobalLayoutListener _listener;
  16. protected override void OnCreate(Bundle savedInstanceState)
  17. {
  18. View = new AvaloniaView(this);
  19. if (ViewContent != null)
  20. {
  21. View.Content = ViewContent;
  22. }
  23. if (Avalonia.Application.Current.ApplicationLifetime is SingleViewLifetime lifetime)
  24. {
  25. lifetime.View = View;
  26. }
  27. base.OnCreate(savedInstanceState);
  28. SetContentView(View);
  29. _listener = new GlobalLayoutListener(View);
  30. View.ViewTreeObserver?.AddOnGlobalLayoutListener(_listener);
  31. }
  32. public object Content
  33. {
  34. get
  35. {
  36. return ViewContent;
  37. }
  38. set
  39. {
  40. ViewContent = value;
  41. if (View != null)
  42. View.Content = value;
  43. }
  44. }
  45. public event EventHandler<AndroidBackRequestedEventArgs> BackRequested;
  46. public override void OnBackPressed()
  47. {
  48. var eventArgs = new AndroidBackRequestedEventArgs();
  49. BackRequested?.Invoke(this, eventArgs);
  50. if (!eventArgs.Handled)
  51. {
  52. base.OnBackPressed();
  53. }
  54. }
  55. protected override void OnDestroy()
  56. {
  57. View.Content = null;
  58. View.ViewTreeObserver?.RemoveOnGlobalLayoutListener(_listener);
  59. base.OnDestroy();
  60. }
  61. protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
  62. {
  63. base.OnActivityResult(requestCode, resultCode, data);
  64. ActivityResult?.Invoke(requestCode, resultCode, data);
  65. }
  66. class GlobalLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener
  67. {
  68. private AvaloniaView _view;
  69. public GlobalLayoutListener(AvaloniaView view)
  70. {
  71. _view = view;
  72. }
  73. public void OnGlobalLayout()
  74. {
  75. _view.TopLevelImpl?.Resize(_view.TopLevelImpl.ClientSize);
  76. }
  77. }
  78. }
  79. }