单击有时在溢出菜单中的菜单项 [英] Click on menu-item that is sometimes in the overflow-menu

查看:71
本文介绍了单击有时在溢出菜单中的菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前要单击有时在溢出菜单中某些设备上的菜单项,我正在执行以下操作:

currently to click on menu-item that is sometimes on some devices in the overflow-menu I am doing the following:

fun invokeMenu(@IdRes menuId: Int, @StringRes menuStringRes: Int) {
 try {
  onView(withId(menuId)).perform(click())
 } catch (nmv: NoMatchingViewException) {
  openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getInstrumentation().targetContext)
  onView(withText(menuStringRes)).perform(click())
 }
}

但是我正在寻找一种更好的方法-理想情况下,我只需要知道menu-id即可.您如何在意式浓缩咖啡测试中做到这一点?

But I am searching for a better approach - ideally something where I just have to know the menu-id. How do you do this in your espresso tests?

推荐答案

不幸的是,您无法实现理想的情况.这是由于支持库的构建.

Unfortunately, your ideal case cannot be acomplished. This is due to the construction of support libraries.

让我们从 PopupMenu ,其中引用了

Let's start from PopupMenu, which has a reference to MenuPopupHelper, which has reference to MenuPopup. This is an abstract class extended ie. by StandardMenuPopup. It has reference to MenuAdapter. If you look into the line 92 of MenuAdapter you will see, the line:

itemView.initialize(getItem(position), 0);

这是关键方法调用.可以在 ActionMenuItemView

This is the key method invocation. It can be invoked either in ActionMenuItemView or ListMenuItemView. Their implementations differ in the case, that id is attached to ActionMenuItemView, and is not attached to ListMenuItemView

此外,

Moreover, MenuAdapter.getItemId(int position) returns just position. The id of menu item is lost in overflow menu.

但是,您的代码可以简化为一个衬里.定义一个函数:

Hovewer, your code can be simplified to one liner. Define a function:

public static Matcher<View> withMenuIdOrText(@IdRes int id, @StringRes int menuText) {
    Matcher<View> matcher = withId(id);
    try {
        onView(matcher).check(matches(isDisplayed()));
        return matcher;
    } catch (Exception NoMatchingViewException) {
        openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getInstrumentation().getTargetContext());
        return withText(menuText);
    }
}

用法:

onView(withMenuIdOrText(R.id.menu_id, R.string.menu_text)).perform(click());

这篇关于单击有时在溢出菜单中的菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆