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.
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.
我通过使用以下两种方法做到了这一点:
@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);
}
链接地址: http://www.djcxy.com/p/92980.html
上一篇: 检测用户何时解除软键盘
下一篇: 防止软键盘被解雇