gpt4 book ai didi

android - 在 .NET MAUI(特别是 Android)中 Hook 键盘事件

转载 作者:行者123 更新时间:2023-12-05 08:10:39 27 4
gpt4 key购买 nike

我正在移植我在 Xamarin Forms 中制作原型(prototype)的 Android 应用程序。我定位的设备具有必须触发应用程序中的操作的硬件按钮。在 Xamarin 中,我能够覆盖 ICallback.OnKeyDown(Keycode keyCode,KeyEvent e)Activity .我没能在 MAUI 中找到任何等效项。我期待 <InputBinding/>像 WPF 或者可能是事件或重写 Element .有什么办法可以做到这一点?甚至可能使用特定于 Android 的代码?

最佳答案

我找到的一个解决方案(仅适用于 Android)是这样的(从我对另一个问题的回答中复制:MAUI How to use KeyEvent.Callback in an Android app):

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

    #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. 为您想要对键使用react的每个页面实现此接口(interface)。示例:

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

希望对您有所帮助。

关于android - 在 .NET MAUI(特别是 Android)中 Hook 键盘事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71976350/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com