I have added a scrollview and the subchilds inside the scrollview. At some point i need to scroll to a specific view.
<scrollview>
1. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
2. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
3. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
4. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
5. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
6. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
7. <linearlayout>
<textview></textview>
<textview></textview>
</linearlayout>
<button>
</button>
</scrollview>
The above layout was created dynamically. so i can't have the xml file posted here. Layout creation is completely dynamic. Even the number of child view inside the linearlayout may also vary.
So when i click on the button i need to get scrolled to a particular view say here when i click on button i need to scroll to the linear layout 4. I tried with the scrollTo method but it scrolls to the top of the scrollview.
Please provide some suggestions.
try this:
insideView.getY()
will not work below API Level 11, for API Level below 11 you can replaceinsideView.getY()
withinsideView.getTop()
I think I have found more elegant and error prone solution using
No math involved, and contrary to other proposed solutions, it will handle correctly scrolling both ways up and down.
It is a good idea to wrap it into
postDelayed
to make it more reliable, in case theScrollView
is being changed at the momentJust nice isn`t?
Since you can know the child
LinearLayout
that you need to scroll to, how about trying this.More information on scrollTo as well as smoothScrollTo
You can use method smoothScrollTo to scroll to specific view in scroll view. - Example:
Good luck!
Try to call
view.requestFocus()
on the view you want to scroll to.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