带有 CollapsingToolbarLayout 的 NestedScrollView 如何滚动到 EditText?

How can a NestedScrollView with a CollapsingToolbarLayout scroll to an EditText?

我在 Android Studio 中有一个类似于 ScrollingActivity 预设的布局。我已将 content_scrolling 中的 TextView 替换为包含 20 个 EditText 组件的 LinearLayout

为了在我聚焦 EditText 时保持工具栏在屏幕上,我还在 AndroidManifest.xml 中的 activity 添加了 android:windowSoftInputMode="adjustResize"

我的问题是 NestedScrollView 没有正确滚动到聚焦的 EditText。当 Toolbar 没有完全折叠时,NestedScrollView 不会向上滚动得足够远。 Toolbar 也不会崩溃。

明显的解决方案是在 OnFocusChangeListener 中调用 scrollTo,但这不会折叠 Toolbar

如何让 NestedScrollView 滚动到 EditText,就像我用手指那样?

我找到了一种滚动到 NestedScrollView 中的视图的方法。这应该在键盘打开后执行。

public static void nestedScrollToView(NestedScrollView nestedScrollView, View v, View rootView) {
    nestedScrollView.startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
    int[] scrolledBy = new int[2];
    int rootBottom = getBottomOnScreen(rootView);
    int viewBottom = getBottomOnScreen(v);
    int toScrollBy = viewBottom - rootBottom;
    if (toScrollBy > 0) {
        boolean preScrollSuccess = nestedScrollView.dispatchNestedPreScroll(0, toScrollBy, scrolledBy, null);
        if (preScrollSuccess) {
            boolean scrollSuccess = nestedScrollView.dispatchNestedScroll(0, 0, 0, toScrollBy, null);
        }
        nestedScrollView.scrollBy(0, toScrollBy - scrolledBy[1]);
    }
}

public static int getBottomOnScreen(View view) {
    int[] location = new int[2];
    view.getLocationOnScreen(location);
    return location[1] + view.getHeight();
}