答案 0 :(得分:0)
您需要创建自定义匹配器:
public static Matcher<View> nthChildOf(final Matcher<View> parentMatcher, final int childPosition) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("with "+childPosition+" child view of type parentMatcher");
}
@Override
public boolean matchesSafely(View view) {
if (!(view.getParent() instanceof ViewGroup)) {
return parentMatcher.matches(view.getParent());
}
ViewGroup group = (ViewGroup) view.getParent();
return parentMatcher.matches(view.getParent()) && group.getChildAt(childPosition).equals(view);
}
};
}
使用它:
onView(nthChildOf(withId(R.id.directParentLinearLayout), 0).check(matches(withText("I am the first child"));
在您的情况下,您还需要检查具有唯一ID的布局的后代:
onView(nthChildOf(allOf(withId(R.id.directParentLinearLayout), isDescendantOfA(withId(R.id.linearLayoutWithUniqueId))), 0).check(matches(withText("I am the first child"));