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.
To hide keyboard, use the following code. InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); inputMethodManager. hideSoftInputFromWindow(v. getApplicationWindowToken(),0);
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With