Forcefully dismissing Keyboard in Xamarin Forms…

Wait… what? You want to forcefully dismiss your keyboard? A-B-S-O-L-U-T-E-L-Y!

Thanks to my experience in  working with high-expectation- seniors at my company, who demands me to push the limits of the Xamarin Forms Framework (frankly I love it, although it is kind of exhausting at times), I keep on sharing cool stuff which is quite out of the norm. And heyyy buckle up, since this is one of those instances where I pushed the limitations of Xamarin Forms! 😉

Once upon a time…

So there was this one time where I had to mimic a translucent layer on top of a login screen, where once the user enters username and password, I would simple capture a screenshot, blur it, and display as a blurred view on top of the page. But the problem there was as soon as user hits “Enter” on the keyboard, the screenshot will be captured but the keyboard would also be visible in the screenshot, since keyboard still stays up until a new layer is popped on top of the page (until the Entry’s focus is dismissed). 😦

Thereby the screenshot and the blurred view had the Keyboard visibility, which was pretty ugly, and my UX Lead wasn’t happy about it (perfectionists! lol).

“YOU MUST GET RID OF THE KEYBOARD VISIBILITY INSTANTLY, NO EXCUSE!”, demanded the UX Lead. 😮

Although this was no way possible out of the box from Xamarin Forms, I was asked to get rid of it one way or the other.

Nah I Didn’t give up!

You might think it’s just a matter of dismissing the focus of the Entry’s Completed event, but hell no it wasn’t! Because there was a specific delay from the Completed event to the keyboard dismissal event firing, which caused our screenshot capturing to capture the page with the Keyboard in view. 😮

So I knew I had to override or interrupt or short-wire the keyboard dismissal event myself forcefully. 😉

So after trying out many different solutions to get rid of the Keyboard visibility when the screenshot was captured, which ended up failing, I finally had the moment of “eureka!”.

le moment of eureka! 😀

Basically, what I did was to create a dependency service which would forcefully dismiss the keyboard, as in, push down the keyboard from which ever the current view of focus.

Sounds pretty simple eh? nah it wasn’t. lol

Up on the Entry’s Completed event I would first of all call up on my custom Keyboard dismissal service and then perform the screen capture and blurring view effect and so on. Which worked out pretty nicely!

Behold the results…

Yeah here’s something I built up to demonstrate the awesomeness of this hack!

How cool is that right? 😉

Besides the coolness, now you might ask what else could this be used for? Isn’t that obvious bro? 😛

Instances where,

  • you want to limit the user from entering text into an Entry after a given timeout?
  • may be dismiss the keyboard after a certain text length is reached?
  • instantly dismiss the keyboard straight from the ViewModel itself without having to go through a UI Event chain?

and so many other aspects, or it might as well be the same situation I had. 😉

Let me show you how it’s done…

So there’s no doubt we need to drill down to the native level when we try to push the limits of Xamarin Forms Framework, as usual.

In Android we could gain the access for the InputMethodManager which gives us the capability to hide the keyboard on demand.

And on iOS we use the UIApplication instance which gives us the access to the PresentedViewController property (current active ViewController), in return allowing us to call the EndEditing on its View to resign the first responder.

Finally I unite those two native calls via dependency service and be used from Xamarin Forms PCL level.

Here’s how to code it…

Blah blah blah.. yeah I talk too much when I’m enthusiastic about a hack I came across lol! 😀

First step create the interface for the keyboard dismissal service…

namespace WhateverYourNamespace
{
    /// <summary>
    /// Forcefully dismiss the keyboard
    /// </summary>
    public interface IForceKeyboardDismissalService
    {
        void DismissKeyboard();
    }
}

 

Now we could use this interface to do the native implementations which could be used via DependencyService of Xamarin Forms.

Next native hacking… or short circuiting you could say!

This is the time for native project level implementation of our service. Go ahead create your platform specific implementation of the IForceKeyboardDismissalService interface.

So for Android, we need to access the current Activity to access the InputMethodManager, for which we would use the Plugin.CurrentActivity library. So if you don’t have it, you might as well go ahead add that to your solution via nuget before implementing the below.

[assembly: Xamarin.Forms.Dependency(typeof(AndroidForceKeyboardDismissalService))]
namespace WhateverYourNamespace.Droid
{
    public class AndroidForceKeyboardDismissalService : IForceKeyboardDismissalService
    {
        public void DismissKeyboard()
        {
            InputMethodManager imm = InputMethodManager.FromContext(CrossCurrentActivity.Current.Activity.ApplicationContext);

            imm.HideSoftInputFromWindow(
                CrossCurrentActivity.Current.Activity.Window.DecorView.WindowToken, HideSoftInputFlags.NotAlways);
        }
    }
}

 

As you can see we are calling up the HideSoftInputFromWindow() method to dismiss the Keyboard via the InputMethodManager instance we retrieved.

Oh don’t forget to add the assembly attributes to register this for the Xamarin Forms DependencyService.

Then on iOS, we already have the singleton access to UIApplication where we are given access to the active PresentedViewController, which holds the instance for the current active view controller.

[assembly: Xamarin.Forms.Dependency(typeof(IosForceKeyboardDismissalService))]
namespace WhateverYourNamespace.iOS
{
    public class IosForceKeyboardDismissalService : IForceKeyboardDismissalService
    {
        public void DismissKeyboard()
        {
            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                var window = UIApplication.SharedApplication.KeyWindow;
                var vc = window.RootViewController;
                while (vc.PresentedViewController != null)
                {
                    vc = vc.PresentedViewController;
                }

                vc.View.EndEditing(true);
            });

        }
    }
}

 

Alright we are then calling the EndEditing() method from the current active View related to the active ViewController. There we are passing true as the parameter to let it know we mean business! 😛 lol uikit/uiview/1619630-endediting

Alright now time for the consumption of some cool code.

Consume it. (not literally) 😛

Here’s how you could use the above awesome service in Xamarin Forms.

DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();

 

That’s it!

Where’s the cool demo? 😮

Now don’t worry I shall not leave you hanging fellas!

You may be wondering where’s the cool implementation you saw at the beginning of the post… 😉
 

Here I have shared it on my github: UdaraAlwis/XFForcefulKeyboardDismiss

Alright, happy coding fellas! 😀

Enjoy and Share!

-Udara Alwis

6 thoughts on “Forcefully dismissing Keyboard in Xamarin Forms…

  1. I just wanted to try it on Android, but unfortunately it doesn’t work: CrossCurrentActivity.Current.Activity is always null. I implemented it exactly as described. I am using the latest versions of Xamarin .Net and Android. Do you have any idea what that could be?
    I am thankful for every help

    Like

Leave a reply to Buddhima Kudagama Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.