Search code examples
androidhideandroid-softkeyboardandroid-custom-keyboard

How to prevent the keyboard hide from view


Have a webview on activity, i need the keyboard always shown on the page regardless of the input (May not input on some page).

Also the keyboard should not be hidden when user press button or any click event.

I tried below options (tried with all flag types) but couldn't find one.

InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_SHOWN);

Solution

  • The below answer works only when we have the single activity and a webview. Not tested for large application.

    The answer is from customising the keyboard InputMethodService.

    hideWindow() is an override method we can restrict the keyboard hide,

    showKeyboardAlways and activity are static variables. The keyboard restriction will work only for the current application not for all.

    @Override
    public void hideWindow() {
        if (!showKeyboardAlways || SoftKeyboard.activity == null) {
            super.hideWindow();
        }
    }
    

    This will prevent the activity back press event, we need to implement the logic as given below

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && SoftKeyboard.activity != null) {
            SoftKeyboard.activity.onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }