How to hide Android soft keyboard on EditText

前端 未结 16 1151
长发绾君心
长发绾君心 2020-11-27 14:38

I have an Activity with some EditText fields and some buttons as a convenience for what normally would be used to populate those fields. However when we the user touches on

16条回答
  •  孤街浪徒
    2020-11-27 15:19

    After long time looking into TextView class I found a way to prevent keyboard to appears. The trick is hide it right after it appears, so I searched a method that is called after keyboard appear and hide it.

    Implemented EditText class

    public class NoImeEditText extends EditText {
    
        public NoImeEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        /**
         * This method is called before keyboard appears when text is selected.
         * So just hide the keyboard
         * @return
         */
        @Override
        public boolean onCheckIsTextEditor() {
            hideKeyboard();
    
            return super.onCheckIsTextEditor();
        }
    
        /**
         * This methdod is called when text selection is changed, so hide keyboard to prevent it to appear
         * @param selStart
         * @param selEnd
         */
        @Override
        protected void onSelectionChanged(int selStart, int selEnd) {
            super.onSelectionChanged(selStart, selEnd);
    
            hideKeyboard();
        }
    
        private void hideKeyboard(){
            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getWindowToken(), 0);
        }
    }
    

    and style

    
    

提交回复
热议问题