我想在活动调用 onCreate() 和 onResume() 时测试键盘可见性。
如何测试使用 espresso 时是否显示键盘?
我知道,这个问题已经足够老了,但它没有任何公认的答案。 在我们的 UI 测试中,我们使用这种方法,它使用一些 shell 命令:
/**
* 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)
}
}
希望,这对某人有用
fun isKeyboardShown(): Boolean {
val inputMethodManager = InstrumentationRegistry.getInstrumentation().targetContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
return inputMethodManager.isAcceptingText
}
找到
另一个技巧可能是检查您知道键盘显示时将被覆盖的视图的可见性。不要忘记考虑动画...
使用 espresso 和 hamcrest 进行 NOT 匹配器的仪器测试,例如:
//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()));
这对我有用。
private boolean isSoftKeyboardShown() {
final InputMethodManager imm = (InputMethodManager) getActivityInstance()
.getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isAcceptingText();
}
@igork 答案的 Java 版本。
这个方法对我有用
val isKeyboardOpened: Boolean
get() {
for (window in InstrumentationRegistry.getInstrumentation().uiAutomation.windows) {
if (window.type == AccessibilityWindowInfo.TYPE_INPUT_METHOD) {
return true
}
}
return false
}
fun checkIsKeyboardDisplayed(expectedIsDisplayed: Boolean) {
val actualIsDisplayed: Boolean
val checkKeyboardCmd = "dumpsys input_method | grep mInputShown"
try {
actualIsDisplayed = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
.executeShellCommand(checkKeyboardCmd).contains("mInputShown=true")
} catch (e: IOException) {
throw RuntimeException("Keyboard check failed", e)
}
Assert.assertTrue(actualIsDisplayed == expectedIsDisplayed)
}`enter code here`
您可以使用标准 insets API 来断言软键盘可见。
view.rootWindowInsets.isVisible(WindowInsets.Type.ime())
如果您使用 compose-ui-test,您可以使用其
waitUntil { }
API:
@get:Rule val rule = createAndroidComposeRule<TestActivity>()
rule.waitUntil {
rule.activity.window.decorView.rootWindowInsets.isVisible(WindowInsets.Type.ime())
}