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

Android listview 如何单击ListView特定行位置的视图,android-listview,position,row,android-espresso,ui-testing,Android Listview,Position,Row,Android Espresso,Ui Testing,我有一个列表视图: 我想单击ListView中的特定按钮 如果要使用onData选择器进行选择: onData(withId(R.id.button)) .inAdapterView(withId(R.id.list_view)) .atPosition(1) .perform(click()); 我得到了这个错误: android.support.test.espresso.PerformExc

我有一个列表视图:

我想单击ListView中的特定按钮

如果要使用onData选择器进行选择:

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;
        }
    };
}
onData()
需要您感兴趣的项目的对象匹配器。如果您不关心适配器中的数据,可以使用
Matchers.anywhere()
来有效匹配适配器中的所有对象。或者,您可以为您的项创建数据匹配器(取决于存储在适配器中的数据),并将其传递给更确定的测试

至于按钮-您正在寻找的是一个
onChildsView()
方法,该方法允许传递listitem子体的viewmatcher,该子体在
onData().atPosition()中匹配

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

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

谢谢我以前没看过这个onChildsView。顺便说一句,nthchildgender函数可能对其他内容有用:)
    onData(anything()).inAdapterView(withId(R.id.list_view))
            .atPosition(1)
            .onChildView(withId(R.id.button))
            .perform(click());