需要一种在MAUI的Editor/Entry字段中隐藏软键盘的方法。

14

我在这个链接中找到了一个看起来很有用的内容:

Xamarin Forms中的禁用键盘输入控件

但是它似乎只在Xamarin Forms中起作用。 我甚至在我的MAUI应用程序中使用它,但它根本没有效果!

我之所以要这样做,是因为我想启用对编辑器字段的焦点,但又不想触发软键盘(用于条形码扫描器字段)。

谢谢。

7个回答

16

它比你想象的更简单 :)

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

}

}


2
确实更简单了,谢谢。 - bryanjez
我曾尝试运行txt.Unfocus(),但没有效果。感谢您提供的解决方案。 - Xusan

12
  • 在 MAUI 中显示软键盘,请将焦点设置到可编辑的控件。

  • 在 MAUI 中隐藏软键盘,请从可编辑控件中移除焦点。您可以通过代码或当用户单击按钮时简单地移动焦点。

  • 以上行为在 Xamarin Forms 中运作良好,但是 MAUI 目前存在一个错误。一旦软键盘被打开,它就无法被隐藏。

  • 目前的解决方法是禁用编辑控件然后再启用,这样可以隐藏键盘,以下是代码片段: this.DescriptionEditor.IsEnabled = false; this.DescriptionEditor.IsEnabled = true;

    请参见下面的链接: 如何在 Xamarin Forms 中通过按钮按下来关闭键盘


喜欢这个答案!它告诉你哪里出了问题,还告诉你如何使其正常工作。谢谢! - balintn

9
在MAUI中,没有必要创建界面...只需在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();
            }
        }
    }
}

在Platforms/iOS/KeyboardHelper.cs中

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

这就是全部内容。

然后在您的应用程序中只需调用:

Platforms.KeyboardHelper.HideKeyboard();

调用函数。将运行的类取决于平台。


iOS示例中的代码已经过时,在iOS 13+中不再适用。 - Tony Lugg
@TonyLugg 你可以用以下代码替换那一行UIApplication.SharedApplication.Delegate.GetWindow().EndEditing(true);我现在无法测试它。 - Michele
你在哪里准确地调用Platforms.KeyboardHelper.HideKeyboard()方法? - Wasyster
@Wasyster 在我的情况下,我在“命令按钮单击”事件的开始运行它,只是为了隐藏键盘,因为用户刚刚在输入字段中插入了一些数据。举个例子:` private async Task cmdLogin_Click() { KeyboardHelper.HideKeyboard(); if (!string.IsNullOrEmpty(txtUserName.Text) && !string.IsNullOrEmpty(txtPassword.Text)) { ...` - Michele

3

你需要首先创建一个接口。

 public interface IKeyboardHelper
{
    public void HideKeyboard();
}

您需要在Platforms> Android > Dependencies中创建相关的类。 示例代码:

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();
        }
       
    }
}

命名空间应该具备以下特点:

[assembly: Dependency(typeof(DroidKeyboardHelper))]

在 app.xaml.cs 中注册

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

然后在调用位置使用

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

0

我只是想补充一下,我发现将entry类进行子类化很有帮助。这样做可以避免你在每个地方都调用隐藏键盘的方法。因此,只要你在所有标签中使用CustomEntry,就可以顺利进行了。 (请注意,这篇文章与其他文章一起阅读,特别是Michele的文章。)

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


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

0
为了解决这个问题,我使用了以下方法(使用this(引用说是Alexandar)和this):
在MauiProgram中添加builder后:
 builder
             .UseMauiCompatibility()
             .ConfigureMauiHandlers((handlers) => {
 #if ANDROID
                         handlers.AddCompatibilityRenderer(typeof(yournamespaceofhelper.SoftkeyboardDisabledEntry),typeof(yournamespaceonAndroid.SoftkeyboardDisabledEntryRenderer)); #endif})

2. 创建一个帮助器(你将使用它来禁用键盘):

public class SoftkeyboardDisabledEntry : Entry
{

}

在平台/Android上创建渲染器。你将使用自定义的输入框,每次在输入框中输入时会使其失去焦点,并且每当输入框的属性更改时,它将保留您在其中编写的内容但不会显示出来。这样做的一个大缺陷是,如果您使用(例如在我的情况下是磁条卡读取器),读卡器写入得非常快,以至于输入框会获得焦点并失去焦点,从而导致键盘出现。为了使键盘不向用户显示,正在进行延迟处理。
在Platforms/Android上创建渲染器:
[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 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); } } } }

回答你对亚历山大说的问题,如果你触摸了编辑器,键盘将会保持隐藏

附注:我找不到让代码可读的方法,如果有人能够编辑它,将不胜感激


嗨@Leandro,我已经测试了上面的内容,好的,所以每当我触摸输入字段中的文本时,键盘不会弹出>>这很好。但是每当调用myEntry.Text.Insert("New Text")方法时,软键盘就会立即弹出。注意:我在某个按钮点击事件中调用了myEntry.Text.Insert方法。 - Wal.H

0
    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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接