我正在使用Monogame和Xamarin为android创建一个游戏。我面临的一个主要问题是从软键盘中准确地获取键盘输入。我尝试将文本放入EditText中,然后使用处理程序将文本转发到游戏中的文本框中。我遇到的问题是,为了从EditText获得键盘输入,我必须更改ContentView,这将使游戏不再可见。
我发现一些较旧的手机在活动中不能正确响应OnKeyUp或DispatchKeyEvent方法(例如,backspace不起作用或有延迟,并且经常一些键不能很好地响应)。我也尝试过直接从视图中使用KeyListener,但这也导致了一些键的延迟。
在主活动中,我将ContentView设置为游戏:
protected override void OnCreate(Bundle bundle)
{
_game = new Game1();
SetContentView((View)_game.Services.GetService(typeof(View)));
var inputMethodManager = (InputMethodManager)this.Application.GetSystemService("input_method");
var textWatcher = new TextWatcher(_game, this, inputMethodManager);
}
然后,当我显示软键盘时,我在实现ITextWatcher接口的TextWatcher类中有以下代码:
public void ShowKeyboard(object sender, string e)
{
if (this._inputMethodManager.IsAcceptingText)
return;
_layout = new LinearLayout(_activity);
//Without this line, the TextWatcher does not capture input text. But with this code, it takes the view away from the game
_activity.SetContentView(_layout);
var orientation = _activity.RequestedOrientation;
if (orientation == ScreenOrientation.Portrait || orientation == ScreenOrientation.ReversePortrait)
_layout.Orientation = Android.Widget.Orientation.Vertical;// (LinearLayout.VERTICAL);
else
_layout.Orientation = Android.Widget.Orientation.Horizontal;// (LinearLayout.VERTICAL);
//Add the EditText to the layout
_layout.AddView(_textEditor);
_textEditor.RequestFocus();
if (!string.IsNullOrEmpty(e))
{
_textEditor.Text = e;
_textEditor.SelectAll();
}
_inputMethodManager.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);
}
如何在不更改视图的情况下从EditText获取文本输入?
发布于 2019-05-23 05:18:52
您可以使用MonoGames KeyboardInput.Show
方法。
var name = await KeyboardInput.Show("Name", "What's your name?", "Player");
如果你需要自己做这件事,我会查看上面方法的Android源代码。在此file中称为PlatformShow
):
来自源代码的主要观点是:
Game.Activity.RunOnUiThread(()
https://stackoverflow.com/questions/56263110
复制相似问题