Click on menu-item that is sometimes in the overflow-menu

痴心易碎 提交于 2019-12-05 17:53:07

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

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

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

Usage:

onView(withMenuIdOrText(R.id.menu_id, R.string.menu_text)).perform(click());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!