其他分享
首页 > 其他分享> > android – 单击有时在溢出菜单中的菜单项

android – 单击有时在溢出菜单中的菜单项

作者:互联网

目前点击溢出菜单中某些设备上的菜单项我正在执行以下操作:

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())
 }
}

但我正在寻找一种更好的方法 – 理想情况下,我必须知道菜单ID.你如何在浓咖啡测试中做到这一点?

解决方法:

不幸的是,你的理想情况无法完成.这是由于支持库的构建.

让我们从PopupMenu开始,它引用了MenuPopupHelper,引用了MenuPopup.这是一个扩展的抽象类ie.它参考了StandardMenuPopup.如果您查看MenuAdapter的第92行,您会看到,该行:

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

这是关键方法调用.它可以在ActionMenuItemViewListMenuItemView中调用.它们的实现在这种情况下有所不同,即id is attached to ActionMenuItemViewis not attached to ListMenuItemView

而且,MenuAdapter.getItemId(int position)只返回位置.菜单项的ID在溢出菜单中丢失.

Hovewer,您的代码可以简化为一个班轮.定义一个函数:

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());

标签:android,android-espresso,optionmenu
来源: https://codeday.me/bug/20190527/1165415.html