Search code examples
androidinputlibgdxandroid-softkeyboardback-button

LibGDX - how to catch a backbutton inside a TextField with Android Keyboard visible?


I'm trying to catch the Back button while the TextField is focused (keyboard is visible).

I have already tried with Multiplexer - setting the 'BackProcessor' on the top of the stages - it doesn't work:

InputProcessor backProcessor = new InputAdapter() {
        @Override
        public boolean keyDown(int keycode) {

            if ((keycode == Input.Keys.BACK) )
            {
                Gdx.app.log("INPUT", "BACK");
            }
            return false;
        }
    };

    InputMultiplexer multiplexer = new InputMultiplexer(backProcessor,
            loginStage,registerStage);
    Gdx.input.setInputProcessor(multiplexer);

Also, I tried in the render method with:

if(Gdx.input.isKeyDown(Keys.BACK)

Doesn't work too.

Above solutions work perfectly EXCEPT the moment, when the keyboard is visible.

What I'm trying to achieve? I need to catch the Back Button when the onScreenKeyboard is visible.

Edit

I also tried with TextFieldListener but 'BackButton' is the one key that hasn't any 'char code' so it can't be catched there:

public void keyTyped(TextField textField, char c)

FINAL EDIT

As LibGDX authors said - there's no way to retrieve this in a normal way cause the back button is proccessed outside of application while it's pressed when keyboard is visible. Android solution is to override EditText's onPreKeyIme() but LibGDX TextField has nothing to do with Android's one and there's no connection.

If there's anyone that could point any solution to this problem, I'd be grateful.


Solution

  • Rewrite your GDX Launcher class using this tutorial: https://github.com/libgdx/libgdx/wiki/Admob-in-libgdx

    Then, you'll have your RelativeLayout so you can override your dispatchKeyEventPreIme() method which will catch events before they're sent to the IME ;)

    RelativeLayout layout = new RelativeLayout(this) {
                @Override
                public boolean dispatchKeyEventPreIme(KeyEvent event) {
    
    
                    if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                        if(event.getAction() == KeyEvent.ACTION_DOWN){
                            // back pressed                 }
    
                    }
                    return super.dispatchKeyEventPreIme(event);
                }
            };