tags:

views:

221

answers:

3

I have the activity with several input fields. When activity started soft keyboard is showed. When back button pressed soft keyboard closes and to close activity need to press back button one more time.

So the question: is it possible intercept back button to close soft keyboard and finish activity in one press of back button without creating custom InputMethodService?

P.S.: I know how intercept back button in other cases - onKeyDown() or onBackPressed() but in this case it's not works: only second press of back button is intercepted.

+1  A: 

How are you showing the soft keyboard?

If you are using InputMethodManager.showSoftInput(), you can try passing in a ResultReceiver and implementing onReceiveResult() to handle RESULT_HIDDEN

http://developer.android.com/reference/android/view/inputmethod/InputMethodManager.html

superuser
Sounds good, but `showSoftInput()` doesn't show keyboard at my phone and emulator, so I use `toggleSoftInput()`
Sergey Glotov
A: 

Try this code in your BackPressed implementation(http://stackoverflow.com/questions/3988478/block-back-button-in-android/3988567#3988567):

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

I suggest you to have a look @ http://stackoverflow.com/questions/1109022/how-to-close-hide-the-android-soft-keyboard

100rabh
I've already tried this, but it still need two presses on back button. As I understand it the first click is intercepted by soft keyboard so `onBackPressed()` doesn't work. And only after the second press program falls into the `onBackPressed()`.
Sergey Glotov
100rabh
+2  A: 

It seems there is no reliable way to do it:

  1. Key events are eaten by soft keyboard.
  2. There is no way (event) to know when soft keyboard is shown/hidden.

See this thread.

Peter Knego