【问题标题】:Match background color of listview row Espresso匹配列表视图行 Espresso 的背景颜色
【发布时间】:2015-12-02 11:02:10
【问题描述】:

我有一个 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;
}

在测试中,我想检查列表中的某个元素是否具有 Color LTGRAY。我创建了一个自定义匹配器:

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]);
        }
    };
}

尝试测试

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

我得到一个空指针异常。

【问题讨论】:

    标签: java android-layout android-listview android-espresso matcher


    【解决方案1】:

    以下似乎对我有用:

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

    自定义匹配器在哪里:

    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: ");
            }
        };
    }
    

    这是一个三列列表视图,其中每行包含一个带有 3 个子 TextView 的 LinearLayout。 "withText("itemtext")" 匹配第一列中的元素/TextView。此列中的元素是唯一的。

    【讨论】:

    • 我用这个((ColorDrawable) row.getBackground()).getColor() 作为(row.background as ColorDrawable).color 但我遇到了这个错误android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.ColorDrawable
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    相关资源
    最近更新 更多