Android ViewPager中的Espresso Recylerview匹配多个视图

Android ViewPager中的Espresso Recylerview匹配多个视图,android,android-fragments,android-recyclerview,android-espresso,Android,Android Fragments,Android Recyclerview,Android Espresso,如何将一个片段作为Viewpager的目标,该片段实现了一个ID与多个视图匹配的RecylerView? 我有一个主活动,它有一个Viewpager。Viewpager有5个选项卡。在这5个选项卡中,我使用RecylerView在每个选项卡中加载图像 RecylerView XML在不同的片段中重复使用,因此当使用Espresso访问它时,它会保持ID匹配多个视图 <android.support.v7.widget.RecyclerView xmlns:android="http

如何将一个片段作为Viewpager的目标,该片段实现了一个ID与多个视图匹配的RecylerView?

我有一个主活动,它有一个Viewpager。Viewpager有5个选项卡。在这5个选项卡中,我使用RecylerView在每个选项卡中加载图像

RecylerView XML在不同的片段中重复使用,因此当使用Espresso访问它时,它会保持ID匹配多个视图

<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
所以它崩溃并指出一个错误

android.support.test.espresso.AmbiguousViewMatcherException:'with id:com.example.app:id/recycler_view'匹配层次结构中的多个视图。 问题视图在下面用“****匹配****”标记

//列出不同的层次结构

View Hierarchy:

View Hierarchy:
+>DecorView{id=-1, visibility=VISIBLE, width=720, height=1280, 
  has-focus=false, has-focusable=true, has-window-focus=true, 
  is-clickable=false, is-enabled=true, is-focused=false, 
  is-focusable=false, is-layout-requested=false, is-selected=false, 
  root-is-layout-requested=false, has-input-connection=false, x=0.0, 
  y=0.0, child-count=1}

//...

在使用
ViewPager
时,我遇到了同样的问题,并将
isDisplayed()
子句添加到
ViewMatcher
中,为我解决了这个问题(尽管,与浓缩咖啡中的所有东西一样,它有时可能会变脆)

onView(allOf(isDisplayed(),带id(R.id.recycler\u视图)))
.perform(recycleServiceActions.ActionItemPosition(2,单击());

我所做的是为每个片段设置不同的内容描述,Espresso支持
hasContentDescription()
withContentDescription()

我已经解决了这个问题,解决方法是唯一实际可见的项目的宽度和高度与相应布局中指定的值完全匹配。所有其他视图寻呼机项目都具有默认维度

因此,我创建了一个简单的匹配器:

private val sizeMatcher = object : TypeSafeMatcher<View>(){
    override fun describeTo(description: Description?) {
        description?.appendText("with expected size")
    }
    override fun matchesSafely(item: View?): Boolean {
        return item != null && (item.height > DEFAULT_HEIGHT || item.width > DEFAULT_WIDTH)
    } 
}

显示阈值很小(80),当浏览页面刚刚滑动时,Espresso不会等待它将视图滚动到屏幕边框并完全显示出来。谢谢,但这不起作用。错误:recycler_视图,并在屏幕上显示给用户)“匹配层次结构中的多个视图。isDisplayed()保存了我的一天,(我在一个表格布局中有多个不同选项卡的RecycleView)。@TosinOnikute如何解决此问题?如何将内容描述设置为片段实例?我没看到二传手。我认为片段布局的根视图的内容描述是可能的。
private val sizeMatcher = object : TypeSafeMatcher<View>(){
    override fun describeTo(description: Description?) {
        description?.appendText("with expected size")
    }
    override fun matchesSafely(item: View?): Boolean {
        return item != null && (item.height > DEFAULT_HEIGHT || item.width > DEFAULT_WIDTH)
    } 
}
fun checkDisplayed(viewId: Int) {
    Espresso.onView(Matchers.allOf(ViewMatchers.withId(viewId), ViewMatchers.isDisplayingAtLeast(80), sizeMatcher)).check(ViewAssertions.matches(ViewMatchers.isDisplayingAtLeast(80)))
}