title: Android Espresso GridView scroll to each item and perform a click on them
body: <p>I have a GridView loaded with data, and some items in the grid are "group" items
  that contain a different set of data. The GridView can scroll if there is
  a lot of data.</p>
  
  <p>On some devices the GridView has three columns and on others there are only two columns depending on the device screen width.</p>
  
  <p>What I need to test is to scroll to a particular(with text) item in the grid, open it and then close it(back button=simpleClick). Then scroll to a second item with a particular text and open and then close it(back button=simpleClick).</p>
  
  <p>I have tried several approaches with swipes, and then performing clicks
  on them, but this approach fails as you need to know exactly how many
  swipes/scrolls to perform before I can click to open the item group - device specific which is bad. Also performing too many scrolls than what is required to reach the bottom of the screen seems to slowdown the test !!quite!! a bit. </p>
  
  <pre><code>   private void scrollDown() {
          Log.d(TAG, "scrollDown: ");
          onView(withId(R.id.main_grid))
                  .perform(swipeUp());
      }
  
      private void scrollUp() {
          Log.d(TAG, "scrollUp: ");
          onView(withId(R.id.main_grid))
                  .perform(swipeDown());
  
      }
  
  private void clickOn(final String text) {
  
      onView(withText(new Matcher&lt;String&gt;() {
              @Override
              public boolean matches(Object item) {
  
                  if (item instanceof String) {
                      if (((String) item).contains(text))
                          return true;
                      else
                          return false;
                  }
                  return false;
              }
  
              @Override
              public void describeMismatch(Object item, Description mismatchDescription) {
  
              }
  
              @Override
              public void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
  
              }
  
              @Override
              public void describeTo(Description description) {
  
              }
      }))
          .perform(click());
  }
  </code></pre>
  
  <p>I have tried this as well, but focus gets set to each Item
  but as it reaches the end of the screen, one needs to scroll manually
  on the device - it does not scroll the screen.</p>
  
  <pre><code>for (int i = 0 ; i &lt; 20; i++) {
                 onData(anything())
                         .inAdapterView(allOf(withId(R.id.main_grid), isDisplayed()))
                         .atPosition(i)
                         .check(matches(isDisplayed()));
  }
  </code></pre>
  
  <p>I have also tried using the onData which I cannot get to succeed(compile/build),
  as I am using a CursorLoader and a ResourceCursorAdapter. </p>
  
  <p>Any Example to solve my test case would great. </p>