Prevent softkeyboard dismiss on the android back button press

This question already has an answer here:

  • Close/hide the Android Soft Keyboard 69 answers

  • create one custom EditText like follow with one interface:

    public class CustomEditText extends EditText {
    
    
        public void setHandleDismissingKeyboard(
            handleDismissingKeyboard handleDismissingKeyboard) {
               this.handleDismissingKeyboard = handleDismissingKeyboard;
        }
    
        private handleDismissingKeyboard handleDismissingKeyboard;
    
        public interface handleDismissingKeyboard {
            public void dismissKeyboard();
        }
    
        @SuppressLint("NewApi")
        public CustomEditText(Context context, AttributeSet attrs,
                                 int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
            // TODO Auto-generated constructor stub
        }
    
        public CustomEditText(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
        }
    
        public CustomEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            // TODO Auto-generated constructor stub
        }
    
        public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            // TODO Auto-generated constructor stub
        }
    
    
        @Override
        public boolean onKeyPreIme(int keyCode, KeyEvent event) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_UP) {
                handleDismissingKeyboard.dismissKeyboard();
                return true;
            }
            return super.dispatchKeyEvent(event);
        }
    

    then in your activity create initialize your CustomEditText and use:

    customEditText.setHandleDismissingKeyboard(this);
    

    then implement class and override method and put your code in that

    for more info about my answer all thing you need is onKeyPreIme , you can override that in your EditText class ( as i post for you ) to handle all key on that, like back Key or any other keyboard key, I put one inner interface in custom class to get call back from this class to each activity or class that you want, you can do that with static method too, and as you want prevent from dismissing keyboard you can just return true in that.

    for using CustomEditText you can use xml or in java, define that and initialize that like other widget ( Button , TextView , ... ), and only different is you need define this in your xml like :

     <yourPackage.CustomEditText ..... />
    
    链接地址: http://www.djcxy.com/p/16600.html

    上一篇: 如何隐藏Android软键盘?

    下一篇: 防止软键盘在Android后退按钮上关闭