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

时间:2015-11-12 10:03:06

标签: android android-edittext android-collapsingtoolbarlayout nestedscrollview

我有一个像Android Studio中ScrollingActivity预设的布局。我已将TextView替换为content_scrollingLinearLayout填充了20个EditText个组件。

要在关注EditText时将工具栏保留在屏幕上,我还在android:windowSoftInputMode="adjustResize"的活动中添加了AndroidManifest.xml

我的问题是NestedScrollView无法正确滚动到焦点EditText。当Toolbar未完全折叠时,NestedScrollView无法向上滚动。 Toolbar也不会崩溃。

明显的解决方案是在scrollTo中调用OnFocusChangeListener,但这不会导致Toolbar崩溃。

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

1 个答案:

答案 0 :(得分:0)

I figured out a way to scroll to a view in a NestedScrollView. This should be executed after the keyboard has been opened.

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();
}