Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss keyboard on button press in Xamarin Forms

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.

like image 236
BillF Avatar asked May 25 '15 11:05

BillF


People also ask

How to disable keyboard in Xamarin Forms?

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.

How do I hide the keyboard on my Android?

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.


2 Answers

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();
like image 191
dreeves Avatar answered Sep 28 '22 09:09

dreeves


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.

like image 42
Alex Avatar answered Sep 28 '22 08:09

Alex