AvaloniaView.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using Android.Content;
  3. using Android.Runtime;
  4. using Android.Views;
  5. using Android.Widget;
  6. using Avalonia.Android.Platform.SkiaPlatform;
  7. using Avalonia.Controls;
  8. using Avalonia.Controls.Embedding;
  9. using Avalonia.Rendering;
  10. namespace Avalonia.Android
  11. {
  12. public class AvaloniaView : FrameLayout
  13. {
  14. private readonly EmbeddableControlRoot _root;
  15. private readonly ViewImpl _view;
  16. private IDisposable? _timerSubscription;
  17. public AvaloniaView(Context context) : base(context)
  18. {
  19. _view = new ViewImpl(context);
  20. AddView(_view.View);
  21. _root = new EmbeddableControlRoot(_view);
  22. _root.Prepare();
  23. }
  24. public object Content
  25. {
  26. get { return _root.Content; }
  27. set { _root.Content = value; }
  28. }
  29. public override bool DispatchKeyEvent(KeyEvent e)
  30. {
  31. return _view.View.DispatchKeyEvent(e);
  32. }
  33. public override void OnVisibilityAggregated(bool isVisible)
  34. {
  35. base.OnVisibilityAggregated(isVisible);
  36. OnVisibilityChanged(isVisible);
  37. }
  38. protected override void OnVisibilityChanged(View changedView, [GeneratedEnum] ViewStates visibility)
  39. {
  40. base.OnVisibilityChanged(changedView, visibility);
  41. OnVisibilityChanged(visibility == ViewStates.Visible);
  42. }
  43. private void OnVisibilityChanged(bool isVisible)
  44. {
  45. if (isVisible)
  46. {
  47. if (AvaloniaLocator.Current.GetService<IRenderTimer>() is ChoreographerTimer timer)
  48. {
  49. _timerSubscription = timer.SubscribeView(this);
  50. }
  51. _root.Renderer.Start();
  52. }
  53. else
  54. {
  55. _root.Renderer.Stop();
  56. _timerSubscription?.Dispose();
  57. }
  58. }
  59. class ViewImpl : TopLevelImpl
  60. {
  61. public ViewImpl(Context context) : base(context)
  62. {
  63. View.Focusable = true;
  64. View.FocusChange += ViewImpl_FocusChange;
  65. }
  66. private void ViewImpl_FocusChange(object sender, FocusChangeEventArgs e)
  67. {
  68. if(!e.HasFocus)
  69. LostFocus?.Invoke();
  70. }
  71. protected override void OnResized(Size size)
  72. {
  73. MaxClientSize = size;
  74. base.OnResized(size);
  75. }
  76. public WindowState WindowState { get; set; }
  77. public IDisposable ShowDialog() => null;
  78. }
  79. }
  80. }