Scroll to a specific view in scroll view Scroll to a specific view in scroll view android android

Scroll to a specific view in scroll view


If child that we need to scroll to is not a direct child then above solutions don't work

I have used below solution in my project, sharing it may be helpful to others

/** * Used to scroll to the given view. * * @param scrollViewParent Parent ScrollView * @param view View to which we need to scroll. */private void scrollToView(final ScrollView scrollViewParent, final View view) {    // Get deepChild Offset    Point childOffset = new Point();    getDeepChildOffset(scrollViewParent, view.getParent(), view, childOffset);    // Scroll to child.    scrollViewParent.smoothScrollTo(0, childOffset.y);}/** * Used to get deep child offset. * <p/> * 1. We need to scroll to child in scrollview, but the child may not the direct child to scrollview. * 2. So to get correct child position to scroll, we need to iterate through all of its parent views till the main parent. * * @param mainParent        Main Top parent. * @param parent            Parent. * @param child             Child. * @param accumulatedOffset Accumulated Offset. */private void getDeepChildOffset(final ViewGroup mainParent, final ViewParent parent, final View child, final Point accumulatedOffset) {    ViewGroup parentGroup = (ViewGroup) parent;    accumulatedOffset.x += child.getLeft();    accumulatedOffset.y += child.getTop();    if (parentGroup.equals(mainParent)) {        return;    }    getDeepChildOffset(mainParent, parentGroup.getParent(), parentGroup, accumulatedOffset);}


This should do the trick:

View targetView = findViewById(R.id.DESIRED_VIEW_ID);  targetView.getParent().requestChildFocus(targetView,targetView);

public void RequestChildFocus (View child, View focused)

child - The child of this ViewParent that wants focus. This view will contain the focused view. It is not necessarily the view that actually has focus.

focused - The view that is a descendant of child that actually has focus


try this:

ScrollView sv = // your scrollviewView insideView = // find the View that you need to scroll to which is inside this ScrollViewsv.scrollTo(0, (int)insideView.getY());

insideView.getY() will not work below API Level 11, for API Level below 11 you can replace insideView.getY() with insideView.getTop()