B T B T - 1 year ago 147
Android Question

AutoCompleteTextView: Remove soft keyboard on back press instead of suggestions

When using

, the dropdown 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 (this is even more of a problem when the device is in landscape orientation). Navigating the list is a lot easier without the keyboard hogging the screen space. Unfortunately, the default behaviour removes the list first when you press the back key (even though in the software versions of the back key it is showing the image that says 'pressing this will hide the keyboard').

Here's a barebones example that demonstrates what I'm talking about:

public class Main2 extends Activity {
private static final String[] items = {

protected void onCreate(Bundle savedInstanceState) {

AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
actv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));

LinearLayout ll = new LinearLayout(this);


Besides the fact that this is unintuitive (the back key hint is suggesting that the back press will be sent to the keyboard), it makes navigating
suggestions extremely tiresome.

What is the least intrusive way (e.g. catching the back in on
in every activity and routing it accordingly would definitely not be ideal) to make the first back press hide the keyboard, and the second remove the suggestion list?

Answer Source

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

    public class CustomAutoCompleteTextView extends AutoCompleteTextView {

        public CustomAutoCompleteTextView(Context context) {

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

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

        public boolean onKeyPreIme(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing()) {
                InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

                    return true;

            return super.onKeyPreIme(keyCode, event);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download