26

I found what seems to be useful in this link:

A Keyboard disabled Entry control in Xamarin Forms

But it seems that it only works in Xamarin Forms. I even used it in my MAUI app, but it simply has no effect !

The reason I am looking to do this is because I want to enable focus on the Editor field but without triggering the soft keyboard (for a barcode scanner field)

Thanks.

11 Answers 11

29

it's more simple than you think :)

private void SingInButton_Clicked(object sender, EventArgs e)
{
    //Trick To Hide VirtualKeyboard
    PasswordEntry.IsEnabled = false;
    PasswordEntry.IsEnabled = true;

}

}

Sign up to request clarification or add additional context in comments.

3 Comments

I was doing txt.Unfocus() but it didn't work. Thanks for your solution.
Unbelievable! Can't believe this is the fix, lol. After years of developing XF and creating hacks for a buggy framework, we are forced into MAUI and given worse. Thanks for the trick.
Although this might do the trick it's just a hacky solution. It's like turning off the TV by unplugging from the wall. If there is platform specific code to achieve your needs, you should 100% go for that insead of reinventing the wheel. @Michele's answer should be the way to go.
18

Well, in MAUI there's not such need to create an interface...

Just add in Platforms/Android/KeyboardHelper.cs

using Android.Content;
using Android.View.InputMethods;

namespace ApplicationName.Platforms
{
    public static partial class KeyboardHelper
    {
        public static void HideKeyboard()
        {
            var context = Platform.AppContext;
            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();
            }
        }
    }
}

And in Platforms/iOS/KeyboardHelper.cs

using UIKit;

namespace ApplicationName.Platforms
{
    public static partial class KeyboardHelper
    {
        public static void HideKeyboard()
        {
            UIApplication.SharedApplication.Delegate.GetWindow().EndEditing(true);
        }
    }
}

And that's it.

Then in your application just call:

Platforms.KeyboardHelper.HideKeyboard();

to call the function. The class that will be run depends on the platform.

4 Comments

The code in the iOS example is obsolete in iOS 13+.
@TonyLugg you can replace that line with UIApplication.SharedApplication.Delegate.GetWindow().EndEditing(true); I can't test it right now.
Where do you exactly call Platforms.KeyboardHelper.HideKeyboard();
@Wasyster in my case I run it at the beginning of a "command button click" event, just to hide the keyboard that was staying visible because the user was just inserting some data in an Entry field. Just for example: ` private async Task cmdLogin_Click() { KeyboardHelper.HideKeyboard(); if (!string.IsNullOrEmpty(txtUserName.Text) && !string.IsNullOrEmpty(txtPassword.Text)) { ... `
14
  • To show the soft keyboard in MAUI set the focus to an editable control.

  • To hide the soft keyboard in MAUI remove the focus from the editable control. You can simply move the focus by code or when the user clicks on a button.

  • The above behaviour works fine in Xamarin Forms, but there is a BUG in MAUI for now. Once the soft keyboard is shown, it does not get hidden.

  • The work around for this issue for now is to disable the edit control then enable it, this will hide the keyboard, a code snippet is given below:

    this.DescriptionEditor.IsEnabled = false; this.DescriptionEditor.IsEnabled = true;

See the link below: How to dismiss keyboard on button press in Xamarin Forms

1 Comment

Love this answer! Tells you what's wrong and also how to make it work. Thank you!
7

For .Net8, use the HideSoftInputOnTapped property on ContentPage to hide keyboard when any of the screen elements are tapped. For more specific control over the keyboard visibility, checkout this.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             ...
             Title="My Page"
             HideSoftInputOnTapped="True"

.NET 8 New features

.NET Upgrade Assistant

1 Comment

Thank you! This must of been the eaiset of all the answers.
4

For others coming to this just hoping to dismiss the keyboard easily when tapping somewhere else on the page, you can enable tap-to-dismiss by adding HideSoftInputOnTapped="True" to the ContentPage XAML

from https://github.com/dotnet/maui/issues/19550#issuecomment-1942035562

1 Comment

This is the way to go. Thankfully all of my pages are of a custom type which inherited from ContentPage. In my base constructor I simply added: HideSoftInputOnTapped = true; That fixed all my issues.
3

You need to create an Interface first.

 public interface IKeyboardHelper
{
    public void HideKeyboard();
}

Than you need to create related class in Platforms> Android > Dependencies Sample code

public class DroidKeyboardHelper : IKeyboardHelper
{
    public DroidKeyboardHelper()
    {
            
    }
    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();
        }
       
    }
}

The name space should have

[assembly: Dependency(typeof(DroidKeyboardHelper))]

Register at app.xaml.cs

  DependencyService.Register<Platforms.Droid.Dependenices.DroidKeyboardHelper>();

Than on the calling location use

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

Comments

2
    public void HideKeyboard()
{
 #if (ANDROID)
    {
        var context = Platform.AppContext;
        var inputMethodManager = context.GetSystemService(Context.InputMethodService) as InputMethodManager;
        if (inputMethodManager != null)
        {
            var activity = Platform.CurrentActivity;
            if (activity != null)
            {
                var token = activity.CurrentFocus?.WindowToken;
                inputMethodManager.HideSoftInputFromWindow(token, HideSoftInputFlags.None);
            }

            if (activity?.Window != null) activity.Window.DecorView.ClearFocus();
        }
    }
#elif (IOS)
    {
        if (UIApplication.SharedApplication?.KeyWindow != null) UIApplication.SharedApplication.KeyWindow.EndEditing(true);
    }
#endif
}

Comments

1

Or you can just use the keyboard extensions in the MAUI Community Toolkit: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/extensions/keyboard-extensions

Comments

1

I solved this by creating a View extension that hides the keyboard. (My code is just targeting iOS)

internal static class ViewExtensions
{
    public static void HideKeyboard(this View view)
    {
#if IOS
        if (view.Handler.PlatformView is UIView nativeView)
        {
            nativeView.EndEditing(true);
        }
#endif
    }
}

I then add a tap gesture recognizer to my background grid

<Grid x:Name="BackgroundGrid">
   <Grid.GestureRecognizers>
     <TapGestureRecognizer Tapped="BackgroundTapped" />
   </Grid.GestureRecognizers> 
  ...
</Grid>

And in the code behind I call the extension method on the background grid

private void BackgroundTapped(object sender, EventArgs e)
{
    BackgroundGrid.HideKeyboard();
}

Comments

0

To solve this i made the following (using this (reference that said alexandar) & this):

  1. On MauiProgram add after builder:

     builder
                 .UseMauiCompatibility()
                 .ConfigureMauiHandlers((handlers) => {
     #if ANDROID
                             handlers.AddCompatibilityRenderer(typeof(yournamespaceofhelper.SoftkeyboardDisabledEntry),typeof(yournamespaceonAndroid.SoftkeyboardDisabledEntryRenderer)); #endif})
    

2.Create a helper (which it's the one you will use it with disabled keyboard):

public class SoftkeyboardDisabledEntry : Entry
{

}
  1. On Platforms/Android create the renderer

     [assembly: ExportRenderer(typeof(SoftkeyboardDisabledEntry), typeof(SoftkeyboardDisabledEntryRenderer))]
    
     namespace YourAppName.Platforms.Android
     {
         public class SoftkeyboardDisabledEntryRenderer : EntryRenderer
         {
             public SoftkeyboardDisabledEntryRenderer(Context context) : base(context)
             {
             }
    
     protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
     {
         base.OnElementChanged(e);
    
         if (e.NewElement != null)
         {
             ((SoftkeyboardDisabledEntry)e.NewElement).PropertyChanging += OnPropertyChanging;
         }
    
         if (e.OldElement != null)
         {
             ((SoftkeyboardDisabledEntry)e.OldElement).PropertyChanging -= OnPropertyChanging;
         }
    
         // Disable the Keyboard on Focus
         this.Control.ShowSoftInputOnFocus = false;
     }
    
     private void OnPropertyChanging(object sender, PropertyChangingEventArgs propertyChangingEventArgs)
     {
         // Check if the view is about to get Focus
         if (propertyChangingEventArgs.PropertyName == VisualElement.IsFocusedProperty.PropertyName)
         {
             // incase if the focus was moved from another Entry
             // Forcefully dismiss the Keyboard 
             InputMethodManager imm = (InputMethodManager)this.Context.GetSystemService(Context.InputMethodService);
             imm.HideSoftInputFromWindow(this.Control.WindowToken, 0);
         }
     }
    
     }
    

    } How this work? you will use a custom entry, that everytime you write something on the entry it's get unfocused, doing this, when the property of the entry changes, it will keep what you write on it but dissappear with the focus / unfocus. The big con of this it's that if you use (for example in my case a magnetic card reader) the reader write so fast so the entry get's focused / unfocused and the keyboard appears. working on it to make a delay so the keyboard doesn't show to the user.

Answering the question you said to alexandar, in case you touched the editor, the keyboard will stay hidden

PD: I couldn't find a way to make the code readable so if someone can edit it, it is appreciated

1 Comment

Hi @Leandro, I was able to test the above, OK so whenever I touch the text in the Entry field, the keyboard won't pop-up >> that's good. But whenever myEntry.Text.Insert("New Text") is called, the soft keyboard pops right back in. Note: I am calling the myEntry.Text.Insert method within some on button clicked event.
0

I just wanted to add to make use of this I found it helpful to subclass the entry class. Doing it this way prevents you from having to call the hide keyboard at every place. So, as long as you just use the CustomEntry in all your tags you're good to go (Realize that this post goes along with the rest of the posts here, in particular Michele's.)

public class CustomEntry : Entry
{
    public CustomEntry()
    {
        Completed += OnCompleted;
    }


    private void OnCompleted(object sender, EventArgs e)
    {
        KeyboardClosingService.HideKeyboard();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.