我要进行单元测试,我必须单击位于recyler视图第一个位置的Textview。我有这个代码
onView(withId(R.id.recyclerViewDevices))
.perform(actionOnItemAtPosition(0, click()));
但我想只在textView中点击,作为" CONNECT"的名称。而不是所有的位置。你能救我吗?
答案 0 :(得分:0)
您可以使用自定义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)));
答案 1 :(得分:0)
使用这段代码:
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)));