繁体   English   中英

MAUI 如何在 Android 应用程序中使用 KeyEvent.Callback

[英]MAUI How to use KeyEvent.Callback in an Android app

该应用程序是为数据采集终端(android)编写的。 它有一个物理键盘。 如果表单上没有文本字段,你能告诉我如何拦截键盘点击吗?

OnKeyListener Class 可以用来处理物理键盘的输入:

 public class MyListener : Java.Lang.Object, Android.Views.View.IOnKeyListener
{
    public bool OnKey(Android.Views.View v, [GeneratedEnum] Keycode keyCode, KeyEvent e)
    {
         return true;// true will intercept keyboard clicks
    }
}

并在表单上没有文本字段时将侦听器添加到条目:

private void entry_Focused(object sender, FocusEventArgs e)
{
    Entry entry = (Entry)sender;
#if ANDROID
    (entry.Handler.PlatformView as AppCompatEditText).SetOnKeyListener(new MyListener());
#endif
 }

当表单有文本时,移除监听器:

Entry entry = (Entry)sender;
#if ANDROID
    (entry.Handler.PlatformView as AppCompatEditText).SetOnKeyListener(null);
#endif

我找到的解决方案是这样的:

  1. 定义一个界面以在您想要对物理键盘键“做出反应”的页面中实现(可选 - 它用于区分您想要对键做出反应的页面与不需要的页面)。 一个样品:

     #if ANDROID using Android.Views; #endif namespace KeyboardTest { public interface IOnPageKeyDown { #if ANDROID /// <summary> /// Called when a key is pressed. /// </summary> /// <param name="keyCode">The code of pressed key.</param> /// <param name="e">Description of the key event.</param> /// <returns> /// Return true to prevent this event from being propagated further, /// or false to indicate that you have not handled this event and it should continue to be propagated. /// </returns> public bool OnPageKeyDown(Keycode keyCode, KeyEvent e); #endif } }
  2. 将此接口实现到您想要对键做出反应的每个页面。 样本:

     #if ANDROID using Android.Views; #endif // Your code here namespace KeyboardTest { public partial class TestPage: ContentPage, IOnPageKeyDown { #if ANDROID public bool OnPageKeyDown(Keycode keyCode, KeyEvent e) { switch (keyCode) { case Keycode.DpadUp: // Your code here return true; case Keycode.DpadDown: // Your code here return true; case Keycode.Enter: // Your code here return true; default: return false; } } #endif } }
  3. 覆盖 Platforms/Android/MainActivity.cs 中的“OnKeyDown”。 样本:

     using Android.App; using Android.Content.PM; using Android.OS; using Android.Runtime; using Android.Views; using AndroidX.Core.View; namespace KeyboardTest; // Your code here public class MainActivity: MauiAppCompatActivity { // Your code here public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e) { Page p = Shell.Current.CurrentPage; if (p is IOnPageKeyDown) { bool handled = (p as IOnPageKeyDown).OnPageKeyDown(keyCode, e); if (handled) return true; else return base.OnKeyDown(keyCode, e); } else return base.OnKeyDown(keyCode, e); } }

我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM