You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MonoGame中如何接收Android系统软键盘输入?

解决MonoGame Android软键盘输入问题

我之前在MonoGame开发Android应用时也踩过类似的键盘输入坑,给你分享两个问题的具体解决方案:

一、Activity中View无法接收键盘事件的问题

你的第一种方法里OnKeyUp和OnKeyPress没触发,核心原因是GameView没有获取焦点,或者事件被MonoGame的输入系统拦截了。可以按以下步骤调整:

  1. 确保View获取焦点
    在OnCreate方法中,给View添加焦点相关配置并主动请求焦点:
protected override void OnCreate(Bundle bundle) {
    base.OnCreate(bundle);
    game = new Game1();
    pView = (View)game.Services.GetService(typeof(View));
    
    // 添加焦点配置
    pView.Focusable = true;
    pView.FocusableInTouchMode = true;
    pView.RequestFocus();
    
    SetContentView(pView);
    game.Run();
    
    // 绑定KeyPress事件
    pView.KeyPress += OnKeyPress;
}
  1. 简化软键盘显示逻辑
    你的ShowKeyboard同时调用了ShowSoftInput和ToggleSoftInput,容易导致逻辑冲突,建议只保留一种方式:
public void ShowKeyboard() {
    TakeKeyEvents(true);
    InputMethodManager inputMethodManager = Application.GetSystemService(Context.InputMethodService) as InputMethodManager;
    // 直接强制唤起软键盘
    inputMethodManager.ShowSoftInput(pView, ShowFlags.Forced);
}
  1. 正确处理KeyPress事件
    修改事件处理方法,记得标记事件是否已处理:
private void OnKeyPress(object sender, View.KeyEventArgs e) {
    if (e.Event.Action == KeyEventActions.Down) {
        // 获取输入的字符
        char inputChar = (char)e.Event.GetUnicodeChar();
        // 测试输出
        System.Diagnostics.Debug.WriteLine($"输入字符: {inputChar}");
    }
    // 若需要让MonoGame继续处理事件则设为false,否则设为true
    e.Handled = false;
}

二、Guide.BeginShowKeyboardInput无法获取输入文本的问题

你之前的回调写法有误,必须调用Guide.EndShowKeyboardInput方法才能获取用户输入的文本,而不是直接解析IAsyncResult。调整后的代码如下:

void KeyboardCallback(IAsyncResult Result) {
    // 通过End方法获取输入结果
    string userInput = Guide.EndShowKeyboardInput(Result);
    
    if (userInput != null) {
        // 用户点击了确认按钮,处理输入内容
        System.Diagnostics.Debug.WriteLine("用户输入: " + userInput);
    } else {
        // 用户取消了输入操作
        System.Diagnostics.Debug.WriteLine("用户取消输入");
    }
}

void CreateButtonClicked(Panel panel) {
    // Android是单玩家环境,PlayerIndex.One完全适用
    ar = Guide.BeginShowKeyboardInput(PlayerIndex.One, "Game1", "Enter a username", "", KeyboardCallback, null);
}

这个方法是MonoGame封装的跨平台键盘输入方案,比自己处理Activity键盘事件更稳定,推荐优先使用。

内容的提问来源于stack exchange,提问作者szMuzzyA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:51:55