SoftKeyboardListner.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Android.Content;
  5. using Android.OS;
  6. using Android.Util;
  7. using Android.Views;
  8. using Avalonia.Input;
  9. namespace Avalonia.Android
  10. {
  11. class SoftKeyboardListner : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener
  12. {
  13. private const int DefaultKeyboardHeightDP = 100;
  14. private static readonly int EstimatedKeyboardDP = DefaultKeyboardHeightDP + (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop ? 48 : 0);
  15. private readonly View _host;
  16. private bool _wasKeyboard;
  17. public SoftKeyboardListner(View view)
  18. {
  19. _host = view;
  20. }
  21. public void OnGlobalLayout()
  22. {
  23. int estimatedKeyboardHeight = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip,
  24. EstimatedKeyboardDP, _host.Resources.DisplayMetrics);
  25. var rect = new global::Android.Graphics.Rect();
  26. _host.GetWindowVisibleDisplayFrame(rect);
  27. int heightDiff = _host.RootView.Height - (rect.Bottom - rect.Top);
  28. var isKeyboard = heightDiff >= estimatedKeyboardHeight;
  29. if (_wasKeyboard && !isKeyboard)
  30. KeyboardDevice.Instance.SetFocusedElement(null, NavigationMethod.Unspecified, KeyModifiers.None);
  31. _wasKeyboard = isKeyboard;
  32. }
  33. }
  34. }