如何单击 ListView 特定行位置中的视图

How can I click on a View in ListView specific row position

我有一个 ListView:

我想单击 ListView 中的特定按钮。

如果我想 select 使用 onData select 或者:

onData(withId(R.id.button))
                .inAdapterView(withId(R.id.list_view))
                .atPosition(1)
                .perform(click());

我收到这个错误:

android.support.test.espresso.PerformException: Error performing 'load adapter data' on view 'with id: com.example.application:id/list_view'.
...

我该如何解决这个问题?

我使用了一种不使用 ListView 数据的解决方法,.getPosition(index) 而是检查具有特定 ID 的视图是否是 ListView 特定位置视图的后代。

public static Matcher<View> nthChildsDescendant(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) {

            while(view.getParent() != null) {
                if(parentMatcher.matches(view.getParent())) {
                    return view.equals(((ViewGroup) view.getParent()).getChildAt(childPosition));
                }
                view = (View) view.getParent();
            }

            return false;
        }
    };
}

用法示例:

onView(allOf(
       withId(R.id.button), 
       nthChildsDescendant(withId(R.id.list_view), 1)))
   .perform(click());

onData() 需要您感兴趣的项目的对象匹配器。如果您不关心适配器中的数据,您可以使用 Matchers.anything() 有效地匹配适配器中的所有对象适配器。或者,您可以为您的项目创建一个数据匹配器(取决于存储在适配器中的数据)并将其传入以进行更具确定性的测试。

至于按钮 - 您正在寻找的是一个 onChildsView() 方法,它允许为列表项的后代传递一个视图匹配器,该列表项在 onData().atPosition()

因此,您的测试将如下所示:

    onData(anything()).inAdapterView(withId(R.id.list_view))
            .atPosition(1)
            .onChildView(withId(R.id.button))
            .perform(click());