I want to test keyboard visibility when an activity calls onCreate() and onResume().
How can i test whether or not the keyboard is shown using espresso?
I know, that the question is old enough, but it doesn't have any accepted answer though. In our UI tests we use this method, which uses some shell commands:
/**
* This method works like a charm
*
* SAMPLE CMD OUTPUT:
* mShowRequested=true mShowExplicitlyRequested=true mShowForced=false mInputShown=true
*/
fun isKeyboardOpenedShellCheck(): Boolean {
val checkKeyboardCmd = "dumpsys input_method | grep mInputShown"
try {
return UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
.executeShellCommand(checkKeyboardCmd).contains("mInputShown=true")
} catch (e: IOException) {
throw RuntimeException("Keyboard check failed", e)
}
}
Hope, it'll be useful for someone
another trick could be checking for the visibility of a view that you know is going to be covered when the keyboard is showing. don't forget to take animations into consideration...
instrumentation testing using espresso and hamcrest for the NOT matcher something like:
//make sure keyboard is visible by clicking on an edit text component
ViewInteraction v = onView(withId(R.id.editText));
ViewInteraction v2 = onView(withId(R.id.componentVisibleBeforeKeyboardIsShown));
v2.check(matches(isDisplayed()));
v.perform(click());
//add a small delay because of the showing keyboard animation
SystemClock.sleep(500);
v2.check(matches(not(isDisplayed())));
hideKeyboardMethod();
//add a small delay because of the hiding keyboard animation
SystemClock.sleep(500);
v2.check(matches(isDisplayed()));
This is a kind of trick to check if keyboard is visible, it's not a perfect solution but for me was enough:
Simple code example:
onView(allOf(withId(R.id.myFragment),isDisplayed()));
onView(withId(R.id.myFragment)).perform(pressBack());
onView(allOf(withId(R.id.myFragment),isDisplayed()));
If keyboard is visible means that the second time you press back button the view container is still there ;)
Hope this help!
fun isKeyboardShown(): Boolean {
val inputMethodManager = InstrumentationRegistry.getInstrumentation().targetContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
return inputMethodManager.isAcceptingText
}
found at Google groups