我的 Xamarin 项目中有一个通过 SkiaSharp 呈现的自定义文本条目,我需要访问 Android 键盘才能输入文本。 我可以使用以下命令调出键盘:
Window.DecorView.WindowInsetsController.Show(WindowInsetsCompat.Type.Ime());
但是,当我执行此操作时,软键盘没有任何文本建议等功能,并且在您选择韩语或日语键盘时仅显示英语键盘(我在手机上启用了它们并在其他应用程序中使用)。
我意识到,如果我在
TextView
上调用上面相同的函数,我可以获得更多软键盘功能和额外的键盘语言:
// In MainActivity.cs
private CustomTextView tv;
protected override void OnCreate(Bundle savedInstanceState)
{
...
// Adding the text view to the Xamarin Forms view group.
if (Window.DecorView.FindViewById(Android.Resource.Id.Content) is ViewGroup viewGroup)
{
tv = new CustomTextView(this); // tv is defined in the class.
tv.SetOnKeyListener(new CustomKeyListener());
viewGroup.AddView(tv);
}
}
// I call this elsewhere when I want the keyboard.
public void SummonKeyboard()
{
tv.RequestFocus();
tv.RequestFocusFromTouch();
tv.WindowInsetsController.Show(WindowInsetsCompat.Type.Ime());
}
但是问题是,它阻止我通过 IOnKeyEventListener 接收任何按键事件或覆盖 EditText 中的各种
OnKey...
函数。我可以从中获取任何输入的唯一方法是通过 TextChanged 事件,但这不足以满足我的需求,因为我需要提取精确的按键。
我的班级
CustomTextView
看起来是这样的:
internal class CustomTextView : TextView
{
public CustomTextView(Context context) : base(context)
{
Focusable = true;
FocusableInTouchMode = true;
InputType = Android.Text.InputTypes.ClassText;
}
}
我的班级
CustomKeyListener
看起来是这样的:
internal class CustomKeyListener : Java.Lang.Object, View.IOnKeyListener
{
public bool OnKey(View v, [GeneratedEnum] Keycode keyCode, KeyEvent e)
{
Debug.WriteLine($"Key press triggerred"); // This is never called.
return false;
}
}
如何在使用完整的 Android 软键盘的同时仍然接收按键输入?
但是问题是,它阻止我通过 IOnKeyEventListener 接收任何按键事件或覆盖 EditText 中的各种
函数。OnKey...
注意:当使用 KeyEvent 类和相关 API 处理键盘事件时,预计键盘事件仅来自硬件键盘。切勿依赖接收软输入法(屏幕键盘)上任何键的按键事件。
所以你无法从软键盘事件中获取键码。这是android原生限制。
但如果是物理键盘,则可以使用KeyEvent。你可以看这个例子:MAUI How to use KeyEvent.Callback in an Android app.