Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 410
justin simonelis Avatar asked Jul 29 '10 19:07

justin simonelis


People also ask

How do I dismiss my keyboard on Android?

To hide keyboard, use the following code. InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); inputMethodManager. hideSoftInputFromWindow(v. getApplicationWindowToken(),0);

How to dismiss keyboard in iOS flutter?

TextField is a very common widget in Flutter. When you click on the TextField it opens up the on-screen keyboard. To hide/dismiss the keyboard you have to press the back button in Android and the done button (inside the onscreen keyboard) in iOS.


2 Answers

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.

like image 76
Anton Avatar answered Oct 19 '22 22:10

Anton


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);
}
like image 44
Engin Yapici Avatar answered Oct 19 '22 20:10

Engin Yapici