I have a custom AutoCompleteTextView and on the first back press I want to hide the soft keyboard. On the next back press I want to go back to the previous activity. So broke it down as below:
- If device's back is pressed then hide the soft keyboard instead of dismissing the AutoCompleteTextView or going back to previous activity.
- If device's back is pressed and keyboard is already hidden, then instantly go back to the previous activity.
For part 1, I wrote this inside my custom widget for AutoCompleteTextView:
@Override
public boolean onKeyPreIme(int keyCode, @NonNull KeyEvent event) {
InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing()) {
if(inputManager.hideSoftInputFromWindow(findFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS)){
return true;
}
}
return super.onKeyPreIme(keyCode, event);
}
And this worked fine. For part2, I modified my code and added a listener in my custom AutoCompleteTextView like this:
@Override
public boolean onKeyPreIme(int keyCode, @NonNull KeyEvent event) {
InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing()) {
if(inputManager.isAcceptingText()){
if(inputManager.hideSoftInputFromWindow(findFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS)){
return true;
}
} else {
callback.onSecondClick();
}
}
return super.onKeyPreIme(keyCode, event);
}
public void setCallback(MyAutoCompleteTextViewInterface callback){
this.callback = callback;
}
public interface MyAutoCompleteTextViewInterface{
void onSecondClick();
}
And in my activity, I did:
@Override
public void onSecondClick() {
finish();
}
The problem is that on first back press it does hide the soft keyboard, but on next back press it just dismisses the dropdown. Then I need to press back for the third time in order to get to the previous activity.
I know there are problems with my approach, but unable to figure it out.