justin simonelis
justin simonelis

Reputation: 111

Prevent soft keyboard from being dismissed

There are many questions related to how to programatically show/hide the soft keyboard.

However, as we all know the android back button will cause the keyboard to be dismissed. Is there a way to prevent the user from dismissing the keyboard with a back button press?

I tried to capture the back button, but when the keyboard is displayed onKeyDown in my activity is not invoked when the back key is pressed and soft keyboard is visible.

Any suggestions would be greatly appreciated.

Upvotes: 11

Views: 5369

Answers (2)

Anton
Anton

Reputation: 251

I've found solution:

public class KeyBoardHolder extends EditText {
    public KeyBoardHolder(Context context) {
        super(context);
    }

    public KeyBoardHolder(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public KeyBoardHolder(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public KeyBoardHolder(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return false;
    }
}

This prevents keyboard from being closed by back button.

Upvotes: 8

Engin Yapici
Engin Yapici

Reputation: 6144

I did it by using following two methods:

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK)     
    {
        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput
                (InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    return super.onKeyUp(keyCode, event);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK)     
    {
        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput
                (InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    return super.onKeyDown(keyCode, event);
}

Upvotes: 3

Related Questions