如何在浓缩咖啡中以编程方式单击 Android 手机的“主页”按钮

ale*_*btr 4 java testing android android-espresso

我需要在 Android 手机上模拟 Espresso 中的主页按钮点击。我试过

onView(withId(android.R.id.home)).perform(click());

和 onView(withContentDescription("Navigate up")).perform(click());

正如一些帖子所建议的那样,但它总是无法找到视图。我是 Espresso 的新手,不知道如何调试它。谢谢。

Mik*_*ski 7

最好使用withContentDescription(R.string.abc_action_bar_up_description)而不是“向上导航”,但它无论如何都不像单击主页按钮,它只使用导航栏的“后退”按钮,因此只有在您的应用程序中有它时它才会起作用。

如果你想模拟主页按钮点击并且你正在使用UI Automator库,你可以像这样模拟

fun pressHome() {
    // Might be a good idea to initialize it somewhere else
    val uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
    uiDevice.pressHome()
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想或不能使用 UI Automator,您可以尝试Intrstumentation.sendKeyDownUpSync()使用KeyEvent.KEYCODE_HOME.