0

I have a unit test to do and I have to click on a Textview that is in the first position of a recyler view. I have this code

 onView(withId(R.id.recyclerViewDevices))
                .perform(actionOnItemAtPosition(0, click())); 

but I want to click only in the textView that as the name of "CONNECT" and not in all the position. Can you help me?

Jose
  • 73
  • 3
  • 12
  • I think you have to use onData and onChildView for working with lists. https://google.github.io/android-testing-support-library/docs/espresso/basics/index.html#using-ondata-with-adapterview-controls-listview-gridview- – Christopher Jan 26 '17 at 12:35
  • Possible duplicate of - http://stackoverflow.com/questions/28476507/using-espresso-to-click-view-inside-recyclerview-item – Dibzmania Jan 26 '17 at 12:40

2 Answers2

0

You can achieve it with a custom ViewAction

private class ClickOnTextView implements ViewAction {

    ViewAction click = click();
    int textViewId;

    public ClickOnTextView(int textViewId) {
        this.textViewId = textViewId;
    }

    @Override
    public Matcher<View> getConstraints() {
        return click.getConstraints();

    }

    @Override
    public String getDescription() {
        return " click on TextView with id: " + textViewId;
    }

    @Override
    public void perform(UiController uiController, View view) {
        click.perform(uiController, view.findViewById(textViewId));
    }
}

Then change your code to:

onView(withId(R.id.recyclerViewDevices)).perform(RecyclerViewActions.actionOnItemAtPosition(0, new ClickOnTextView(R.id.CONNECT)));
Gustavo Pagani
  • 6,583
  • 5
  • 40
  • 71
0

Use this piece of code:

public static ViewAction clickChildViewWithId(final int id) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return null;
        }

        @Override
        public String getDescription() {
            return "Click on a child view with specified id.";
        }

        @Override
        public void perform(UiController uiController, View view) {
            View v = view.findViewById(id);
            v.performClick();
        }
    };
}

and use it like this:

onView(allOf(withId(R.id.ID_OF_RECYCLERVIEW), isDisplayed())).perform(RecyclerViewActions.actionOnItemAtPosition(POSITION_IN_RECYCLERVIEW, clickChildViewWithId(R.id.ID_OF_TEXTVIEW)));
matt.mic
  • 185
  • 1
  • 1
  • 12