After much hunting I worked out a way to hide the keyboard on a button press in Xamarin Forms, for the iOS case. So it's shared below.
If anyone can improve it, or share a solution for the Android side, that would be great.
In a native Android project, create a class to hide the keyboard and register the dependency for the same. Hide the soft keyboard using HideSoftInputFromWindow method , and clear the focus using ClearFocus method.
You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow , passing in the token of the window containing your focused view. This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.
I found this useful:
https://forums.xamarin.com/discussion/comment/172077#Comment_172077
Interface:
public interface IKeyboardHelper
{
void HideKeyboard();
}
iOS:
public class iOSKeyboardHelper : IKeyboardHelper
{
public void HideKeyboard()
{
UIApplication.SharedApplication.KeyWindow.EndEditing(true);
}
}
Droid:
public class DroidKeyboardHelper : IKeyboardHelper
{
public void HideKeyboard()
{
var context = Forms.Context;
var inputMethodManager = context.GetSystemService(Context.InputMethodService) as InputMethodManager;
if (inputMethodManager != null && context is Activity)
{
var activity = context as Activity;
var token = activity.CurrentFocus?.WindowToken;
inputMethodManager.HideSoftInputFromWindow(token, HideSoftInputFlags.None);
activity.Window.DecorView.ClearFocus();
}
}
}
Usage in Xamarin Forms:
DependencyService.Get<IKeyboardHelper>().HideKeyboard();
If the removing focus method is not working for you (and it wasn't working for me) after a lot of searching I realized an easy way to force the keyboard to dismiss.
FindViewById<EditText>(Resource.Id.edittextname).Enabled = false;
FindViewById<EditText>(Resource.Id.edittextname).Enabled = true;
That's it. Just disable and enable it and it will close the keyboard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With