Strassenrenner
Strassenrenner

Reputation: 318

Set Item selected in Android Context Menu

In my Activity I have a GridView with a registered ContextMenu. Now I want to test this Activity, therefore I say performLongClick() on first child of the GridView and the context menu opens. Now I want to press the first entry in this menu, is it possible to do that?

public class TestClass extends extends ActivityInstrumentationTestCase2<MainActivity> {
    public void testMe() {
        final GridView gv = getActivity().findViewById(R.id.some_id);
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                gv.getChildAt(0).performLongClick();
            }
        });
        getInstrumenttation().waitForIdleSync();

        //Registered Context Menu opens

        //????some method to get contextMenu and press first item
        //getActivity().getContextMenu().performClick(0); <---
    }
}

Upvotes: 1

Views: 574

Answers (1)

Strassenrenner
Strassenrenner

Reputation: 318

Ok I solved my problem by overriding ´onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info)´ in my MainActivity and set menu as globals variable. After that I can retrieve the ContextMenu in my test class and perform a click:

public void testDelete() {
    performLongClick(gv.getChildAt(1));

    final ContextMenu contextMenu = getActivity().getContextMenu();
    assertTrue(contextMenu != null);

    getActivity().runOnUiThread(new Runnable() {
        public void run() {
            contextMenu.performIdentifierAction(R.id.menuItemId, 0);
        }
    });
    getInstrumentation().waitForIdleSync();
}

Upvotes: 3

Related Questions