10

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.

Wal.H
  • 111
  • 1
  • 5

6 Answers6

10

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;

}

}

devdennis
  • 119
  • 1
  • 4
9
  • 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 hown, it does not get hidden.

  • The work around 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

sohail
  • 99
  • 1
7

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

Just add in Platforms/Android/KeyboardHelper.cs

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

namespace ApplicationName.Platforms
{
    public static partial class KeyboardHelper
    {
        public static void HideKeyboard()
        {
            UIApplication.SharedApplication.KeyWindow.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.

Michele
  • 101
  • 1
  • 6
  • The code in the iOS example is obsolete in iOS 13+. – Tony Lugg Jan 04 '23 at 22:14
  • @TonyLugg you can replace that line with `UIApplication.SharedApplication.Delegate.GetWindow().EndEditing(true);` I can't test it right now. – Michele Jan 05 '23 at 18:05
  • Where do you exactly call Platforms.KeyboardHelper.HideKeyboard(); – Wasyster Jan 21 '23 at 11:50
  • @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)) { ... ` – Michele Jan 25 '23 at 16:36
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();
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

Leandro Toloza
  • 1,655
  • 1
  • 6
  • 24
  • 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. – Wal.H Jan 22 '23 at 13:23
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();
    }
}
aktikt1
  • 29
  • 3