【问题标题】:Click a textview in RecyclerView with Espresso使用 Espresso 在 RecyclerView 中单击文本视图
【发布时间】:2017-01-26 12:23:00
【问题描述】:

我有一个单元测试要做,我必须点击一个位于 recyler 视图第一个位置的 Textview。我有这个代码

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

但我只想在 textView 中单击“CONNECT”的名称,而不是在所有位置。你能帮帮我吗?

【问题讨论】:

标签: android unit-testing android-espresso


【解决方案1】:

您可以通过自定义 ViewAction 来实现它

private class ClickOnTextView implements ViewAction {

    ViewAction click = click();
    int textViewId;

    public ClickOnTextView(int textViewId) {
        this.textViewId = textViewId;
    }

    @Override
    public Matcher<View> getConstraints() {
        return click.getConstraints();

    }

    @Override
    public String getDescription() {
        return " click on TextView with id: " + textViewId;
    }

    @Override
    public void perform(UiController uiController, View view) {
        click.perform(uiController, view.findViewById(textViewId));
    }
}

然后将代码更改为:

onView(withId(R.id.recyclerViewDevices)).perform(RecyclerViewActions.actionOnItemAtPosition(0, new ClickOnTextView(R.id.CONNECT)));

【讨论】:

  • ViewAction click = click();此行在 click() 上给出错误;
  • 添加到您的导入中:import static android.support.test.espresso.action.ViewActions.click;
  • 它没有连接。它保持在活动中并且什么都不做:S
  • 然后尝试here 描述的解决方案
  • 你想点击带有 id "connect" 还是带有 text "connect" 的文本视图?
【解决方案2】:

使用这段代码:

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(allOf(withId(R.id.ID_OF_RECYCLERVIEW), isDisplayed())).perform(RecyclerViewActions.actionOnItemAtPosition(POSITION_IN_RECYCLERVIEW, clickChildViewWithId(R.id.ID_OF_TEXTVIEW)));

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多