Milèstre BV
Aug 05, 2021

Xamarin Forms: Close Keyboard for Entry in DataTemplate


Create an interface class

namespace EasyBridge_App.Interfaces
{
    public interface IKeyboardHelper
    {
        void HideKeyboard();
    }
}


Dependency class in Android

using Android.Content;
using Android.Runtime;
using Android.Views.InputMethods;
using EasyBridge_App.Droid.Helpers;
using EasyBridge_App.Interfaces;
using Xamarin.Essentials;
using Xamarin.Forms;

[assembly: Dependency(typeof(KeyboardHelper))]
namespace EasyBridge_App.Droid.Helpers
{
    [Preserve(AllMembers = true)]
    public class KeyboardHelper : IKeyboardHelper
    {
        public void HideKeyboard()
        {
            var context = Android.App.Application.Context;
            var inputMethodManager = context.GetSystemService(Context.InputMethodService) as InputMethodManager;
            if (inputMethodManager != null)
            {
                var activity = Platform.CurrentActivity;
                var token = activity.CurrentFocus?.WindowToken;
                inputMethodManager.HideSoftInputFromWindow(token, HideSoftInputFlags.None);
                activity.Window.DecorView.ClearFocus();
            }
        }
    }
}


Dependency class in iOS

using EasyBridge_App.Interfaces;
using EasyBridge_App.iOS.Helpers;
using Foundation;
using UIKit;
using Xamarin.Forms;

[assembly: Dependency(typeof(KeyboardHelper))]
namespace EasyBridge_App.iOS.Helpers
{
    [Preserve(AllMembers = true)]
    public class KeyboardHelper : IKeyboardHelper
    {
        public void HideKeyboard()
        {
            UIApplication.SharedApplication.KeyWindow.EndEditing(true);
        }
    }
}


Dependency class in UWP

using EasyBridge_App.Interfaces;
using EasyBridge_App.UWP.Helpers;
using Windows.UI.ViewManagement;
using Xamarin.Forms;
using Xamarin.Forms.Internals;

[assembly: Dependency(typeof(KeyboardHelper))]
namespace EasyBridge_App.UWP.Helpers
{
    [Preserve(AllMembers = true)]
    public class KeyboardHelper : IKeyboardHelper
    {
        private InputPane _inputPane;

        public KeyboardHelper()
        {
            _inputPane = InputPane.GetForCurrentView();
        }

        public void HideKeyboard()
        {
            _inputPane.TryHide();
        }
    }
}
 
Using in shared project

 DependencyService.Get<IKeyboardHelper>().HideKeyboard();

About us

Milèstre is a digital development agency based in Maastricht and operating all over the world. Since 2003 we build software solutions together with established companies and great startups. During the years we have developed a process that enables us to transform ideas into meaningful, intelligent and designfull experiences for mobile and web. A process where strategy, design, development and user experience are playing an important rol.

 

Contact us

Milestre BV
Ambyerstraat Zuid 82
6225 AJ Maastricht
Netherlands

Tel: +31(0)43 - 4070780
Email: info@milestre.nl
Recent Posts

© Copyright 2022 - Milestre BV
Top