android 使用Espresso在RecyclerView项目中单击视图

dsf9zpds  于 2022-12-21  发布在  Android
关注(0)|答案(9)|浏览(124)

如何使用Espresso单击RecyclerView项目中的特定视图?我知道我可以使用以下命令单击位置0的项目:
第一个月
但我需要单击该项目内的特定视图,而不是项目本身。

  • 编辑-
    更准确地说:我有一个RecyclerViewR.id.recycler_view),其中的项目是CardViewR.id.card_view)。在每个CardView中,我有四个按钮(以及其他内容),我想单击特定的按钮(R.id.bt_deliver)。
    我想使用Espresso 2.0的新功能,但我不确定这是否可行。
    如果不可能,我想使用类似这样的代码(使用Thomas Keller代码):
onRecyclerItemView(R.id.card_view, ???, withId(R.id.bt_deliver)).perform(click());

但我不知道该怎么打问号。

idfiyjo8

idfiyjo81#

您可以使用自定义视图操作来完成此操作。

public class MyViewAction {

    public static ViewAction clickChildViewWithId(final int id) {
        return new ViewAction() {
            @Override
            public Matcher<View> getConstraints() {
                return null;
            }

            @Override
            public String getDescription() {
                return "Click on a child view with specified id.";
            }

            @Override
            public void perform(UiController uiController, View view) {
                View v = view.findViewById(id);
                v.performClick();
            }
        };
    }

}

然后,您可以使用单击它

onView(withId(R.id.rv_conference_list)).perform(
            RecyclerViewActions.actionOnItemAtPosition(0, MyViewAction.clickChildViewWithId(R.id. bt_deliver)));
2admgd59

2admgd592#

现在有了android.support.test.espresso.contrib,一切都变得简单了:
1)添加测试依赖项

androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.0') {
    exclude group: 'com.android.support', module: 'appcompat'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude module: 'recyclerview-v7'
}
  • 排除3个模块,因为您很可能已经拥有了这些模块

2)然后做一些像

onView(withId(R.id.recycler_grid))
            .perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));

或者

onView(withId(R.id.recyclerView))
  .perform(RecyclerViewActions.actionOnItem(
            hasDescendant(withText("whatever")), click()));

或者

onView(withId(R.id.recycler_linear))
            .check(matches(hasDescendant(withText("whatever"))));
wlzqhblo

wlzqhblo3#

以下是我如何解决Kotlin中的问题:

fun clickOnViewChild(viewId: Int) = object : ViewAction {
    override fun getConstraints() = null

    override fun getDescription() = "Click on a child view with specified id."

    override fun perform(uiController: UiController, view: View) = click().perform(uiController, view.findViewById<View>(viewId))
}

然后

onView(withId(R.id.recyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(position, clickOnViewChild(R.id.viewToClickInTheRow)))
j9per5c4

j9per5c44#

您可以单击recyclerView第三项,如下所示:

onView(withId(R.id.recyclerView)).perform(
                RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(2,click()))

不要忘记提供ViewHolder类型,以便推理不会失败。

jrcvhitl

jrcvhitl5#

尝试下一种方法:

onView(withRecyclerView(R.id.recyclerView)
                    .atPositionOnView(position, R.id.bt_deliver))
                    .perform(click());

    public static RecyclerViewMatcher withRecyclerView(final int recyclerViewId) {
            return new RecyclerViewMatcher(recyclerViewId);
    }

public class RecyclerViewMatcher {
    final int mRecyclerViewId;

    public RecyclerViewMatcher(int recyclerViewId) {
        this.mRecyclerViewId = recyclerViewId;
    }

    public Matcher<View> atPosition(final int position) {
        return atPositionOnView(position, -1);
    }

    public Matcher<View> atPositionOnView(final int position, final int targetViewId) {

        return new TypeSafeMatcher<View>() {
            Resources resources = null;
            View childView;

            public void describeTo(Description description) {
                int id = targetViewId == -1 ? mRecyclerViewId : targetViewId;
                String idDescription = Integer.toString(id);
                if (this.resources != null) {
                    try {
                        idDescription = this.resources.getResourceName(id);
                    } catch (Resources.NotFoundException var4) {
                        idDescription = String.format("%s (resource name not found)", id);
                    }
                }

                description.appendText("with id: " + idDescription);
            }

            public boolean matchesSafely(View view) {

                this.resources = view.getResources();

                if (childView == null) {
                    RecyclerView recyclerView =
                            (RecyclerView) view.getRootView().findViewById(mRecyclerViewId);
                    if (recyclerView != null) {

                        childView = recyclerView.findViewHolderForAdapterPosition(position).itemView;
                    }
                    else {
                        return false;
                    }
                }

                if (targetViewId == -1) {
                    return view == childView;
                } else {
                    View targetView = childView.findViewById(targetViewId);
                    return view == targetView;
                }

            }
        };
    }
}
7uhlpewt

7uhlpewt6#

你甚至可以推广这种方法来支持更多的动作,而不仅仅是click

fun <T : View> recyclerChildAction(@IdRes id: Int, block: T.() -> Unit): ViewAction {
  return object : ViewAction {
    override fun getConstraints(): Matcher<View> {
      return any(View::class.java)
    }

    override fun getDescription(): String {
      return "Performing action on RecyclerView child item"
    }

    override fun perform(
        uiController: UiController,
        view: View
    ) {
      view.findViewById<T>(id).block()
    }
  }
 
}

对于EditText,你可以这样做:

onView(withId(R.id.yourRecyclerView))
        .perform(
            actionOnItemAtPosition<YourViewHolder>(
                0,
                recyclerChildAction<EditText>(R.id.editTextId) { setText("1000") }
            )
        )
pqwbnv8z

pqwbnv8z7#

以上所有的答案对我来说都不起作用,所以我构建了一个新方法,它搜索单元格内的所有视图,以返回具有所请求ID的视图。它需要两个方法(可以合并为一个):

fun performClickOnViewInCell(viewID: Int) = object : ViewAction {
    override fun getConstraints(): org.hamcrest.Matcher<View> = click().constraints
    override fun getDescription() = "Click on a child view with specified id."
    override fun perform(uiController: UiController, view: View) {
        val allChildViews = getAllChildrenBFS(view)
        for (child in allChildViews) {
            if (child.id == viewID) {
                child.callOnClick()
            }
        }
    }
}

private fun  getAllChildrenBFS(v: View): List<View> {
    val visited = ArrayList<View>();
    val unvisited = ArrayList<View>();
    unvisited.add(v);

    while (!unvisited.isEmpty()) {
        val child = unvisited.removeAt(0);
        visited.add(child);
        if (!(child is ViewGroup)) continue;
        val group = child
        val childCount = group.getChildCount();
        for (i in 0 until childCount) { unvisited.add(group.getChildAt(i)) }
    }

    return visited;
}

最后,您可以通过执行以下操作在Recycler View上使用此功能:

onView(withId(R.id.recyclerView)).perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, getViewFromCell(R.id.cellInnerView) {
            val requestedView = it
}))

如果您想对视图执行其他操作,您可以使用回调来返回视图,或者只构建3-4个不同版本的视图来执行任何其他任务。

1yjd4xko

1yjd4xko8#

我不断尝试各种方法来找出为什么@blade的答案对我不起作用,结果发现我有一个OnTouchListener(),我相应地修改了ViewAction:

fun clickTopicToWeb(id: Int): ViewAction {

        return object : ViewAction {
            override fun getDescription(): String {...}

            override fun getConstraints(): Matcher<View> {...}

            override fun perform(uiController: UiController?, view: View?) {

                view?.findViewById<View>(id)?.apply {

                    //Generalized for OnClickListeners as well
                    if(isEnabled && isClickable && !performClick()) {
                        //Define click event
                        val event: MotionEvent = MotionEvent.obtain(
                          SystemClock.uptimeMillis(),
                          SystemClock.uptimeMillis(),
                          MotionEvent.ACTION_UP,
                          view.x,
                          view.y,
                          0)

                        if(!dispatchTouchEvent(event))
                            throw Exception("Not clicking!")
                    }
                }
            }
        }
    }
mfuanj7w

mfuanj7w9#

首先给予你的按钮一个独特的contentDescriptions,例如“delivery button row 5”。
第一个月
然后滚动到行:
onView(withId(R.id.recycler_view)).perform(RecyclerViewActions.scrollToPosition(5));
然后根据contentDescription选择视图。
onView(withContentDescription("delivery button row 5")).perform(click());
内容描述是使用Espresso的onView并使您的应用更易于访问的绝佳方式。

相关问题