SerCe SerCe - 4 months ago 24
Android Question

Handle back button, in MonoGame on Android

i have a problem with handling back button in my game on android, developed on MonoGame with MonoDroid. I can't catch back button click event.

I tried:

if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
{
LoadingScreen.Load(ScreenManager, true, null, new BackgroundScreen(),
new LevelSelectScreen());
}


And on main Activity

public override bool OnKeyUp(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back)
{
...
return true;
}

return base.OnKeyDown(keyCode, e);
}

public override void OnBackPressed()
{
...
Toast.MakeText(this, keyCode + " key! + " + keyCode.ToString(), ToastLength.Short).Show();
}

public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back)
{
...
return true;
}

return base.OnKeyDown(keyCode, e);
}


Nothing helps, on WP first variant works perfectly

Answer

YEAH! I found solution: When you call

GamePad.GetState(PlayerIndex.One)

in Android GamePadState cleared

public static GamePadState GetState(PlayerIndex playerIndex)
{
    var instance = GamePad.Instance;
    var state = new GamePadState(new GamePadThumbSticks(), new GamePadTriggers(), new GamePadButtons((Buttons)instance._buttons), new GamePadDPad());
    instance.Reset(); // <- CLEAR BUTTONS
    return state;
}

So, do not call GetState in Android several times.