如何在Espresso中编写Android工具栏返回按钮操作的代码

9
在我的Android应用程序中,我有工具栏并需要在Espresso中执行工具栏返回按钮单击操作。我尝试了以下方法,但它不起作用。
onView(withId(R.id.pageToolbar)).perform(click());

需要执行其返回按钮的点击操作。
2个回答

11

我的ContentDescription没有起作用,所以我不得不使用:

        onView(allOf(
            instanceOf(AppCompatImageButton::class.java), withParent(withId(R.id.toolbar))
        ))
            .perform(click())

因为在层次树中我没有办法唯一地识别它:

+-------->AppCompatImageButton{id=-1, visibility=VISIBLE, width=147, height=147, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.Toolbar$LayoutParams@acd01cf, tag=null, root-is-layout-requested=false, has-input-connection=false, x=21.0, y=0.0}

这对我有用:onView(first(allOf(instanceOf(AppCompatImageButton.class),withParent(withId(R.id.toolbar)))))。perform(click()); - DBCrocky
什么是第一? - Skizo-ozᴉʞS ツ

2
如果您的应用程序运行在英语语言环境下,请使用以下内容:
onView(withContentDescription("Navigate up")).perform(click());

为了让它能在任何语言上运行,请使用以下方法:
onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click());

请注意,R.string.abc_action_bar_up_description 来自 AppCompat 支持库。
同时请注意,'Arrow Back' 按钮没有其他唯一的 id,因为 Espresso 将其视为这样:
+------> AppCompatImageButton {id=-1, desc=Navigate up, visibility=VISIBLE,
    width=84, height=68, has-focus=false, has-focusable=false, has-window-focus=true,
    is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true,
    is-layout-requested=false, is-selected=false,
    layout-params = android.support.v7.widget.Toolbar$LayoutParams@1af06e3d,
    tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0}

“Navigate up” 是什么?它是默认文本还是需要更改的内容? - M.A.Murali
onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click()); 这不是默认文本,如果你想要更改,需要在字符串中声明并从这里调用。 - Srinivas Keerthiprakasam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接