AutoCompleteTextView: Remove soft keyboard on back press instead of suggestions

Published Apr 04, 2017

When using, AutoCompleteTextView the drop-down suggestion list appears with the software keyboard still visible. This makes sense, as it is often a lot more efficient to type ensuing characters to narrow the list. But if the user wants to navigate the suggestion list, it becomes extremely tedious with the software keyboard still up.

We can achieve that by override-ing onKeyPreIme in your custom AutoCompleteTextView.

public class CustomAutoCompleteTextView extends AutoCompleteTextView {

        public CustomAutoCompleteTextView(Context context) {
            super(context);
        }

        public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public CustomAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }

        @Override
        public boolean onKeyPreIme(int keyCode, KeyEvent event) {

            if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing()) {

                InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

                if(inputManager.hideSoftInputFromWindow(findFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS)){    
                    return true;
               }
            }

            return super.onKeyPreIme(keyCode, event);
        }

 }
Discover and read more posts from Kuldeep Joshi
get started