I have a very long activity with a scrollview. It is a form with various fields that the user must fill in. I have a checkbox half way down my form, and when the user checks it I want to scroll to a specific part of the view. Is there any way to scroll to an EditText object (or any other view object) programmatically?
Also, I know this is possible using X and Y coords but I want to avoid doing this as the form may changed from user to user.
The answer of Sherif elKhatib can be greatly improved, if you want to scroll the view to the center of the scroll view. This reusable method smooth scrolls the view to the visible center of a HorizontalScrollView.
For a vertical
ScrollView
change thex
andy
position of inputs ofsmoothScroll
. And useview.getTop()
instead ofview.getLeft()
andview.getBottom()
instead ofv.getRight()
.:)
The above answers will work fine if the ScrollView is the direct parent of the ChildView. If your ChildView is being wrapped in another ViewGroup in the ScrollView, it will cause unexpected behavior because the View.getTop() get the position relative to its parent. In such case, you need to implement this:
Examining Android source code, you can find that there already is a member function of
ScrollView
–scrollToChild(View)
– that does exactly what is requested. Unfortunatelly, this function is for some obscure reason markedprivate
. Based on that function I've written following function that finds the firstScrollView
above theView
specified as a parameter and scrolls it so that it becomes visible within theScrollView
:In my case, that's not
EditText
, that'sgoogleMap
. And it works successfully like this.I made a small utility method based on Answer from WarrenFaith, this code also takes in account if that view is already visible in the scrollview, no need for scroll.
In my opinion the best way to scroll to a given rectangle is via
View.requestRectangleOnScreen(Rect, Boolean)
. You should call it on aView
you want to scroll to and pass a local rectangle you want to be visible on the screen. The second parameter should befalse
for smooth scrolling andtrue
for immediate scrolling.