简体   繁体   English

匹配listview行Espresso的背景色

[英]Match background color of listview row Espresso

I have a ListView with rows of different colors created through a custom adapter like: 我有一个ListView,其中包含通过自定义适配器创建的不同颜色的行,例如:

@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;
}

In a test, I would like to check whether a certain element in the list has Color LTGRAY. 在测试中,我想检查列表中的某个元素是否具有Color LTGRAY。 I created a custom matcher: 我创建了一个自定义匹配器:

public static Matcher<Object> backgroundShouldHaveColor(int expectedColor) {
    return viewShouldHaveBackgroundColor(equalTo(expectedColor));
}
private static Matcher<Object> viewShouldHaveBackgroundColor(final Matcher<Integer> expectedObject) {
    final int[] color = new int[1];
    return new BoundedMatcher<Object, View>( 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]);
        }
    };
}

Trying to test with 尝试与

onView(withText("itemtext")).check(matches(backgroundShouldHaveColor(Color.LTGRAY)));

I get a null pointer exception. 我得到一个空指针异常。

The following seems to work for me: 以下内容似乎对我有用:

onView(withChild(withText("itemtext"))) // this matches the LinearLayout or row/convertview
      .check(matches(withBgColor(Color.LTGRAY)));

where the custom matcher is: 自定义匹配器在哪里:

public static Matcher<View> withBgColor(final int color) {
    Checks.checkNotNull(color);
    return new BoundedMatcher<View, LinearLayout>(LinearLayout.class) {
        @Override
        public boolean matchesSafely(LinearLayout row) {
            return color == ((ColorDrawable) row.getBackground()).getColor();
        }
        @Override
        public void describeTo(Description description) {
            description.appendText("with text color: ");
        }
    };
}

This is for a three column listview where each row consists of a LinearLayout with 3 child TextViews. 这是针对三列列表视图的,其中每行包含一个带有3个子TextViews的LinearLayout。 "withText("itemtext")" matches an element/TextView in the first column. “ withText(” itemtext“)”与第一列中的元素/ TextView匹配。 Elements in this column are unique. 此列中的元素是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM