Skip to content

Instantly share code, notes, and snippets.

@trinnguyen
Last active March 15, 2019 12:58
Show Gist options
  • Save trinnguyen/2c3c0881b56ec64e22fecedb9893d35f to your computer and use it in GitHub Desktop.
Save trinnguyen/2c3c0881b56ec64e22fecedb9893d35f to your computer and use it in GitHub Desktop.
Simply approach to detech keyboard visibility changed on Xamarin.Android, based on blog of PDFKit (https://pspdfkit.com/blog/2016/keyboard-handling-on-android/#)
private void AddKeyboardVisibilityHandler()
{
var decorView = Window.DecorView;
decorView.ViewTreeObserver.GlobalLayout += OnViewTreeObserverGlobalLayoutChange;
}
private void RemoveKeyboardVisibilityHandler()
{
var decorView = Window.DecorView;
decorView.ViewTreeObserver.GlobalLayout -= OnViewTreeObserverGlobalLayoutChange;
}
void OnViewTreeObserverGlobalLayoutChange(object sender, EventArgs e)
{
int MinKeyboardHeightPx = 150;
var decorView = Window.DecorView;
decorView.GetWindowVisibleDisplayFrame(_windowVisibleDisplayFrame);
int visibleDecorViewHeight = _windowVisibleDisplayFrame.Height();
// Decide whether keyboard is visible from changing decor view height.
if (_lastVisibleDecorViewHeight != 0)
{
if (_lastVisibleDecorViewHeight > visibleDecorViewHeight + MinKeyboardHeightPx)
{
// Calculate current keyboard height (this includes also navigation bar height when in fullscreen mode).
int currentKeyboardHeight = decorView.Height - _windowVisibleDisplayFrame.Bottom;
// Notify listener about keyboard being shown.
OnKeyboardShown(currentKeyboardHeight);
}
else if (_lastVisibleDecorViewHeight + MinKeyboardHeightPx < visibleDecorViewHeight)
{
// Notify listener about keyboard being hidden.
OnKeyboardHidden();
}
}
_lastVisibleDecorViewHeight = visibleDecorViewHeight;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment