33

I'm trying to test an app and I require to hide the keyboard, because I cannot click button because of it. So, I added Espresso in build.gradle:

androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'

and tried to use this from android.support.test.espresso.action.ViewActions library:

ViewActions.closeSoftKeyboard();

Test runs successfully, but fails after typing some text in EditText in my layout. And keyboard is still there, showing.

P.S. I realized it was keyboard's fault after reading this answer.

Community
  • 1
  • 1
getsadzeg
  • 640
  • 3
  • 9
  • 19

2 Answers2

63

ViewAction on its own does not do anything unless it is used in the ViewInteraction. That means that you need to either chain it with your previous action in perform() like this: onView()..perform(typeText(..), closeSoftKeyboard()) or use a built-in helper which is in Espresso class like this: Espresso.closeSoftKeyboard()

Be_Negative
  • 4,892
  • 1
  • 30
  • 33
  • Yes it solved keyboard problem, but the error stil exists.. Thanks anyway. – getsadzeg Sep 19 '16 at 19:47
  • 6
    They really should give these a different name. Once there's an import, it's not really obvious that a method called "closeSoftKeyboard()" only works when chained to ViewActions. I got stung by this one but your answer helped me. From now on I'll be explicit with Espresso.closeSoftKeyboard(). That's what they do in the examples, I just didn't see why until now :) – Michael Vescovo Mar 08 '17 at 05:33
8

You can implement this:

fun hideKeyboard() {
    onView(ViewMatchers.isRoot()).perform(ViewActions.closeSoftKeyboard())
  }

After that only use this: paymentMethodPage.hideKeyboard()

xsami
  • 1,312
  • 16
  • 31
Tonny Tonny
  • 81
  • 1
  • 1