Reputation: 1192
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?
Upvotes: 23
Views: 9525
Reputation: 3076
You can use the standard insets APIs to assert that the soft keyboard is visible.
view.rootWindowInsets.isVisible(WindowInsets.Type.ime())
If you're using compose-ui-test, you can use its waitUntil { }
API:
@get:Rule val rule = createAndroidComposeRule<TestActivity>()
rule.waitUntil {
rule.activity.window.decorView.rootWindowInsets.isVisible(WindowInsets.Type.ime())
}
Upvotes: 1
Reputation: 1819
This method is working for me
val isKeyboardOpened: Boolean
get() {
for (window in InstrumentationRegistry.getInstrumentation().uiAutomation.windows) {
if (window.type == AccessibilityWindowInfo.TYPE_INPUT_METHOD) {
return true
}
}
return false
}
Upvotes: 1
Reputation: 164
This works for me.
private boolean isSoftKeyboardShown() {
final InputMethodManager imm = (InputMethodManager) getActivityInstance()
.getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isAcceptingText();
}
Java version of @igork's answer.
Upvotes: 0
Reputation: 2938
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
Upvotes: 22
Reputation: 563
fun isKeyboardShown(): Boolean {
val inputMethodManager = InstrumentationRegistry.getInstrumentation().targetContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
return inputMethodManager.isAcceptingText
}
found at Google groups
Upvotes: 7
Reputation: 838
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()));
Upvotes: 0