对于给定的RecyclerView,我可以通过以下方式访问LinearLayout元素:
recyclerView.findViewHolderForAdapterPosition(1)
其中1是RecyclerView中的第二个元素/位置,并返回ViewHolder。
如何访问ViewHolder LinearLayout的子元素?或者有没有办法到达AppCompatTextView元素,以便我可以从该元素中提取文本?
答案 0 :(得分:0)
我创建了RecyclerViewMatcher类,然后是代码
onView(withRecyclerView(R.id.rv_fragment_recipes).atPosition(0))
.check(matches(isDisplayed()));
onView(withRecyclerView(R.id.rv_fragment_recipes).atPositionOnView(0, R.id.tv_recipe_name))
.check(matches(isDisplayed()))
.check(matches(withText("Nutella Pie")));
onView(withRecyclerView(R.id.rv_fragment_recipes).atPositionOnView(0, R.id.tv_servings))
.check(matches(isDisplayed()))
.check(matches(withText("Servings : 8")));
onView(withRecyclerView(R.id.rv_fragment_recipes).atPosition(0))
.perform(click());

public class RecyclerViewMatcher {
private final int recyclerViewId;
public RecyclerViewMatcher(int recyclerViewId) {
this.recyclerViewId = 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) {
String idDescription = Integer.toString(recyclerViewId);
if (this.resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%s (resource name not found)",
new Object[] { Integer.valueOf
(recyclerViewId) });
}
}
description.appendText("with id: " + idDescription);
}
public boolean matchesSafely(View view) {
this.resources = view.getResources();
if (childView == null) {
RecyclerView recyclerView =
(RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
childView = recyclerView.findViewHolderForAdapterPosition(position).itemView;
}
else {
return false;
}
}
if (targetViewId == -1) {
return view == childView;
} else {
View targetView = childView.findViewById(targetViewId);
return view == targetView;
}
}
};
}
}
&#13;
for refernce you can follow this project
如果recyclerView数据不是静态的,则使用IdelingResource