title: Match background color of listview row Espresso
body: <p>I have a ListView with rows of different colors created through a custom adapter like: </p>
  
  <pre><code>@Override
  public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
  
      convertView = mInflater.inflate(R.layout.row_unit, parent, false);
  
      // ...
  
      if( /* some condition */ ) {
          convertView.setBackgroundColor(Color.LTGRAY);
      } else {
          convertView.setBackgroundColor(Color.WHITE);
      }
      return convertView;
  }
  </code></pre>
  
  <p>In a test, I would like to check whether a certain element in the list has Color LTGRAY. I created a custom matcher:</p>
  
  <pre><code>public static Matcher&lt;Object&gt; backgroundShouldHaveColor(int expectedColor) {
      return viewShouldHaveBackgroundColor(equalTo(expectedColor));
  }
  private static Matcher&lt;Object&gt; viewShouldHaveBackgroundColor(final Matcher&lt;Integer&gt; expectedObject) {
      final int[] color = new int[1];
      return new BoundedMatcher&lt;Object, View&gt;( View.class) {
          @Override
          public boolean matchesSafely(View view) {
  
              color[0] =((ColorDrawable) view.getBackground()).getColor();
  
  
              if( expectedObject.matches(color[0])) {
                  return true;
              } else {
                  return false;
              }
          }
          @Override
          public void describeTo(final Description description) {
              // Should be improved!
              description.appendText("Color did not match " + color[0]);
          }
      };
  }
  </code></pre>
  
  <p>Trying to test with</p>
  
  <pre><code>onView(withText("itemtext")).check(matches(backgroundShouldHaveColor(Color.LTGRAY)));
  </code></pre>
  
  <p>I get a null pointer exception.</p>