当条目集中在 Android 中 .net7 上的 Net MAUI 上时,我需要隐藏软键盘,以便从条形码扫描仪输入数据。
到目前为止,我尝试在聚焦时禁用/启用输入,但行为不正确。
我还尝试了一个 KeyBoardHelper,我发现它具有相同的行为(不显示光标或者当输入聚焦时我改变了背景颜色并且这个助手没有改变)。
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();
}
}
}
有没有其他方法可以防止在输入焦点时显示键盘?
Put this in your \Platforms\Android\MainActivity.cs:
-------------------------------------------------------
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
KeyboardService.lastContext = this;
....
}
public void HideKeyboard()
{
try
{
InputMethodManager imm = (InputMethodManager)GetSystemService(InputMethodService);
imm.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
}
catch
{ }
}
public void ShowKeyboard(Android.Views.View view)
{
try
{
InputMethodManager imm = (InputMethodManager)GetSystemService(InputMethodService);
view.RequestFocus();
imm.ShowSoftInput(view, 0);
imm.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);
}
catch (Exception e) { }
}
Create a new file \Platforms\Android\Services\KeyboardService.cs
-----------------------------------------------------------------
using Android.Content;
using Android.OS;
using Android.Views;
internal static partial class KeyboardService
{
public static Context lastContext;
public static bool KeyboardIsVisible = false;
public static void HideKeyboard()
{
((MainActivity)lastContext).HideKeyboard();
KeyboardIsVisible = false;
}
public static void ShowKeyboard(Entry entry)
{
((MainActivity)lastContext).ShowKeyboard((Android.Views.View)entry.Handler.PlatformView);
KeyboardIsVisible = true;
}
}
create the empty counterpart file on the "non android" side (for each platform used) f.e.: yourProject\Services\KeyboardService.cs
----------------------------------------------------------------------------------------------------------------------------------
internal static partial class KeyboardService
{
}
Call the android functions anywhere you need to:
--------------------------------------------------------
KeyboardService.HideKeyboard();
KeyboardService.ShowKeyboard(MyEntryFieldName);
在
Entry
处理程序中:
handler.PlatformView.ShowSoftInputOnFocus = false;
或使用属性映射器在Page
或
MauiProgram
中自定义控件:
Microsoft.Maui.Handlers.EntryHandler.Mapper
.AppendToMapping("ShowSoftInputOnFocus", (handler, view) =>
{
if (view is Entry entry)
{
#if ANDROID
handler.PlatformView.ShowSoftInputOnFocus = false;
#endif
}
});