I have added a scrollview and the subchilds inside the scrollview. At some point i need to scroll to a specific view.
1.
I think I have found more elegant and error prone solution using
ScrollView.requestChildRectangleOnScreen
No math involved, and contrary to other proposed solutions, it will handle correctly scrolling both ways up and down.
void scrollToRow(ScrollView scrollView, LinearLayout linearLayout, TextView textViewToShow) {
Rect textRect = new Rect(); //coordinates to scroll to
textViewToShow.getHitRect(textRect); //fills textRect with coordinates of TextView relative to its parent (LinearLayout)
scrollView.requestChildRectangleOnScreen(linearLayout, textRect, false); //ScrollView will make sure, the given textRect is visible
}
It is a good idea to wrap it into postDelayed
to make it more reliable, in case the ScrollView
is being changed at the moment
private void scrollToRow(final ScrollView scrollView, final LinearLayout linearLayout, final TextView textViewToShow) {
long delay = 100; //delay to let finish with possible modifications to ScrollView
scrollView.postDelayed(new Runnable() {
public void run() {
Rect textRect = new Rect(); //coordinates to scroll to
textViewToShow.getHitRect(textRect); //fills textRect with coordinates of TextView relative to its parent (LinearLayout)
scrollView.requestChildRectangleOnScreen(linearLayout, textRect, false); //ScrollView will make sure, the given textRect is visible
}
}, delay);
}
Just nice isn`t?