まず、以下のように Stage クラスを拡張します。
public static class MyStage extends Stage{
public MyStage(float width, float height, boolean keepAspectRatio, SpriteBatch batch){
super(width, height, keepAspectRatio, batch);
}
@Override
public boolean keyDown(int keyCode) {
if(keyCode==Keys.BACK||keyCode==Keys.MENU){
if(getHardKeyListener()!=null)
getHardKeyListener().onHardKey(keyCode, 1);
}
return super.keyDown(keyCode);
}
@Override
public boolean keyUp(int keyCode) {
if(keyCode==Keys.BACK||keyCode==Keys.MENU){
if(getHardKeyListener()!=null)
getHardKeyListener().onHardKey(keyCode, 0);
}
return super.keyUp(keyCode);
}
/*********************Hard key listener***********************/
public interface OnHardKeyListener{
/**
* Happens when user press hard key
* @param keyCode Back or Menu key (keyCode one of the constants in Input.Keys)
* @param state 1 - key down, 0 - key up
*/
public abstract void onHardKey(int keyCode, int state);
}
private OnHardKeyListener _HardKeyListener = null;
public void setHardKeyListener(OnHardKeyListener HardKeyListener) {
_HardKeyListener = HardKeyListener;
}
public OnHardKeyListener getHardKeyListener() {
return _HardKeyListener;
}
}
次に、Screen
クラスで:
protected final MyStage stage;
public YourScreen(Game game)
{
this.game = game;
stage = new MyStage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true, game.spriteBatch);
Gdx.input.setInputProcessor(stage);
//prevents the app from being pause...
Gdx.input.setCatchBackKey(true);
Gdx.input.setCatchMenuKey(true);
//Sets hard key listener...
stage.setHardKeyListener(new OnHardKeyListener() {
@Override
public void onHardKey(int keyCode, int state) {
if(keyCode==Keys.BACK && state==1){
//do something
}
}
});
}
あなたやこのようなものを探している他の誰かに役立つことを願っています.