How to set id for popup menu items, to be found as view id?

Viewed 1981

Background

Out automatic tests use views' ids to be able to click on them, so we add ids whenever possible.

The problem

For popup menus, sometimes it's needed to populate them dynamically, but as I've found, even when I do add id for each item, the id isn't found, and can't be used. Even using DDMS's feature "dump view hierarchy for UI automator" shows that no view in the popup menu has an id.

What I've tried

This is a sample code of what I use, to try to set an id for the a single menu item.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    View v=findViewById(R.id.button);
    v.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
            final Menu menu = popupMenu.getMenu();
            menu.add(0, R.id.myMenuItem, 0, R.string.app_name).setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(final MenuItem item) {
                    return false;
                }
            }) ;
            popupMenu.show();
        }
    });
}

Note that the id is declared in "ids.xml" file, as such:

<item name="myMenuItem" type="id"/>

And this is what DDMS tool shows me :

enter image description here

The question

How come this code doesn't work as expected (meaning have an id for the menu item view) ? What can I do to make the views in it to have ids? What is the correct way to add ids for menu items that are created dynamically ?

1 Answers
Related