我已经编写了一个ViewAction,用于处理NestedScrollView的子视图滚动。它还考虑到了CoordinatorLayout可能是根布局的情况 - 所以您不必担心工具栏会改变其大小。
以下是一些代码。您需要将此类复制粘贴到项目的某个位置。然后,您可以像这样使用它:
onView(withId(R.id.register_scroll_view))
.perform(CustomScrollActions.nestedScrollTo, click())
重要提示:它不能替代scrollTo()
方法,而是另一种ScrollView滚动视图操作,适用于处理NestedScrollView的情况。
所以我说的就是一个ViewAction:
public class CustomScrollActions {
public static ViewAction nestedScrollTo() {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return Matchers.allOf(
isDescendantOfA(isAssignableFrom(NestedScrollView.class)),
withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE));
}
@Override
public String getDescription() {
return "Find parent with type " + NestedScrollView.class +
" of matched view and programmatically scroll to it.";
}
@Override
public void perform(UiController uiController, View view) {
try {
NestedScrollView nestedScrollView = (NestedScrollView)
findFirstParentLayoutOfClass(view, NestedScrollView.class);
if (nestedScrollView != null) {
CoordinatorLayout coordinatorLayout =
(CoordinatorLayout) findFirstParentLayoutOfClass(view, CoordinatorLayout.class);
if (coordinatorLayout != null) {
CollapsingToolbarLayout collapsingToolbarLayout =
findCollapsingToolbarLayoutChildIn(coordinatorLayout);
if (collapsingToolbarLayout != null) {
int toolbarHeight = collapsingToolbarLayout.getHeight();
nestedScrollView.startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
nestedScrollView.dispatchNestedPreScroll(0, toolbarHeight, null, null);
}
}
nestedScrollView.scrollTo(0, view.getTop());
} else {
throw new Exception("Unable to find NestedScrollView parent.");
}
} catch (Exception e) {
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(e)
.build();
}
uiController.loopMainThreadUntilIdle();
}
};
}
private static CollapsingToolbarLayout findCollapsingToolbarLayoutChildIn(ViewGroup viewGroup) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof CollapsingToolbarLayout) {
return (CollapsingToolbarLayout) child;
} else if (child instanceof ViewGroup) {
return findCollapsingToolbarLayoutChildIn((ViewGroup) child);
}
}
return null;
}
private static View findFirstParentLayoutOfClass(View view, Class<? extends View> parentClass) {
ViewParent parent = new FrameLayout(view.getContext());
ViewParent incrementView = null;
int i = 0;
while (parent != null && !(parent.getClass() == parentClass)) {
if (i == 0) {
parent = findParent(view);
} else {
parent = findParent(incrementView);
}
incrementView = parent;
i++;
}
return (View) parent;
}
private static ViewParent findParent(View view) {
return view.getParent();
}
private static ViewParent findParent(ViewParent view) {
return view.getParent();
}
}
swipeUp()
而不是scrollTo()
。 - Wahib Ul Haq