Search code examples
androidviewandroid-edittextscrollview

How to scroll view to Top of screen


I have a EditText in my android NestedScrollView and I want it to go to top when It's focused, something like this:

enter image description here

I tried:

SmoothScrolling/Scrolling to a direct pixel, SmoothScrolling/Scrolling to the top of the view(or bottom)

none of them work, and not even respond consistently.

Edit:

I got it, will leave the question for documentation porposes.

I got the ScrollView size with

scrollView.getBottom();

And then scrolled to the intended place using:

scrollView.scrollTo(0,2*scrollView.getBottom()/5); //size will vary from view to view

Solution

  • for others who need a solution, here it is for Java:

    /**
         * This function will scroll and bring a view to the top of scrollView
         *
         * @param view target view
         */
        public static void scrollToView(View rootView, ScrollView scrollView, View view) {
            rootView.clearFocus();
    
            int[] locationOfView = new int[2];
            view.getLocationOnScreen(locationOfView);
            int viewY = locationOfView[1];
    
            int[] locationOfScrollView = new int[2];
            scrollView.getLocationOnScreen(locationOfScrollView);
            int scrollY = locationOfScrollView[1];
    
            scrollView.post(() -> scrollView.smoothScrollTo(0, viewY + scrollView.getScrollY() - scrollY));
        }
    

    And here is Kotlin extension function:

    /**
     * Scrolls the ScrollView to bring a specific view to the top.
     *
     * @param target The target view to be brought to the top.
     */
    fun ScrollView.scrollToView(rootView: View, target: View, extraTopMargin: Int = 10.dp()) {
        rootView.clearFocus()
    
        val (_, targetViewY) = IntArray(2).apply { target.getLocationOnScreen(this) }
        val (_, scrollViewY) = IntArray(2).apply { getLocationOnScreen(this) }
    
        post { smoothScrollTo(0, targetViewY + scrollY - scrollViewY - extraTopMargin) }
    }