在Monogame中接收来自Android软键盘的输入

时间:2018-01-20 00:23:27

标签: c# android xamarin monogame on-screen-keyboard

我只是试图接收用户在使用Android系统键盘时按下的字符。 OSK显示正常,但我无法接收用户输入的字符。我尝试过两种不同的方法(我能找到的只有两种)。

第一种方法是使用View类中的Activity对象,如演示here。我无法让它工作,所以我一直在寻找和尝试不同的东西,没有任何效果。

我的Activity班级

[Activity(Label = "Game1"
    , MainLauncher = true
    , Icon = "@drawable/icon"
    , Theme = "@style/Theme.Splash"
    , AlwaysRetainTaskState = true
    , LaunchMode = Android.Content.PM.LaunchMode.SingleInstance
    , ScreenOrientation = ScreenOrientation.Portrait
    , ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.Keyboard | ConfigChanges.KeyboardHidden | ConfigChanges.ScreenSize)]
public class Activity1 : Microsoft.Xna.Framework.AndroidGameActivity
{
    View pView = null;
    Game1 game = null;
    IAsyncResult ar = null;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        game = new Game1();

        pView = (View)game.Services.GetService(typeof(View));
        SetContentView(pView);

        game.Run();
    }

    public void ShowKeyboard()
    {
        TakeKeyEvents(true);
        InputMethodManager inputMethodManager = Application.GetSystemService(Context.InputMethodService) as InputMethodManager;
        inputMethodManager.ShowSoftInput(pView, ShowFlags.Forced);
        inputMethodManager.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);
    }

    public void HideKeyboard()
    {
        InputMethodManager inputMethodManager = Application.GetSystemService(Context.InputMethodService) as InputMethodManager;
        inputMethodManager.HideSoftInputFromWindow(pView.WindowToken, HideSoftInputFlags.None);
        TakeKeyEvents(false);
    }

    public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent e)
    {
        return base.OnKeyUp(keyCode, e); // Never gets called
    }

    private void OnKeyPress(object sender, View.KeyEventArgs e)
    {
         // Never gets called
    }
}

第二种方法使用XNA附带的Guide.BeginShowKeyboardInput()方法。它显示带键盘的文本框。当你点击接受按钮时,会有一个被调用的AsyncCallback。在回调中,我试图弄清楚如何获取用户键入的文本,但无法弄清楚如何。我找不到任何有用的文档来实际从软键盘获取值。

方法2实施

void KeyboardCallback(IAsyncResult Result)
{
    System.Runtime.Remoting.Messaging.AsyncResult res = Result as System.Runtime.Remoting.Messaging.AsyncResult;
}

void CreateButtonClicked(Panel panel)
{
    ar = Guide.BeginShowKeyboardInput(PlayerIndex.One, "Game1", "Enter a username", "", KeyboardCallback, obj);
}

ar是显示键盘方法返回的IAsyncResult对象。我试着查看IAsyncResult对象中的值来查找我输入键盘的文本,但是我没有看到任何内容。

2 个答案:

答案 0 :(得分:1)

我知道我可能为时已晚,但这是您需要做的:

void KeyboardCallback(IAsyncResult Result)
{
    var text = Guide.EndKeyboardInput(result);
    //text now contains your keyboard input
}

void CreateButtonClicked(Panel panel)
{
    ar = Guide.BeginShowKeyboardInput(PlayerIndex.One, "Game1", "Enter a username", "", KeyboardCallback, null);
}

希望有帮助...

答案 1 :(得分:0)

我厌倦了这个键盘记录,我创建了自己的键盘类,其中包含每个字母的简单按钮。 我在textinput-object变为活动状态等时显示它。

可能不是最好的解决方案,但至少它适用于Android和Windows。