9

The picture shows a part of my app, an AutoCompleteTextView with an attached adapter. When the user enters something into that view, autocomplete suggestions are shown.

The problem I have is: when the suggestions are shown and the device's down arrow is pressed, only the suggestions from the AutoCompleteTextView are closed, the keyboard stays open and needs a second tap on the down arrow to disappear.

I do want the suggestions and the keyboard to disappear on the first tap on the down arrow.

I tried overriding onBackPressed but it is not called when the down arrow is tapped, presumably because it's not considered 'back'.

How could I do this?

EDIT: I know how to programmatically hide the keyboard, I guess my problem is to detect the 'down arrow' tap.

enter image description here

fweigl
  • 19,982
  • 18
  • 97
  • 188

3 Answers3

7

Try to override onKeyPreIme() method in your AutoCompleteTextView as follows:

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == 1) {
        super.onKeyPreIme(keyCode, event);
        hideKeyboard()
        return true;
    }
    return super.onKeyPreIme(keyCode, event);
}
Oleg Osipenko
  • 2,350
  • 1
  • 19
  • 28
0

You can try something like this:

private boolean mIsKeyboardShown;
private EditText mSearchTextView;

@Override
protected void onCreate(Bundle bundle)
  ...
  mSearchTextView = (EditText) findViewById(R.id.search);
  View activityRootView = findViewById(R.id.activityRoot);
  activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
      @Override
      public void onGlobalLayout() {
          int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
          // if more than 100 pixels, its probably a keyboard...
          mIsKeyboardShown = (heightDiff > 100);
       }
  });
}

public void onBackPressed() {
  if(mIsKeyboardShown) {
    // close the keyboard
    InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(mSearchTextView.getWindowToken(), 0);
  } else {
    super.onBackPressed();
  }
}

I haven't tried the code but I think this is the right approach.

Kiril Aleksandrov
  • 2,571
  • 18
  • 27
-3
InputMethodManager inputManager = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE); 

inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                     InputMethodManager.HIDE_NOT_ALWAYS);

you need to import android.view.inputmethod.InputMethodManager;

Samvid Kulkarni
  • 1,124
  • 1
  • 13
  • 25