Smoothy scroll to Child in NestedScrollView
The childView
, to which I wanted to scroll, has CardView
parrent, so childView.getTop()
returns the value relative to the CardView
not to the ScrollView
. So, to get top relative to ScrollView
I should get childView.getParent().getParent()
then cast it to View
and call getTop()
.
Scroll position calculates like
int scrollTo = ((View) childView.getParent().getParent()).getTop() + childView.getTop();
nestedScrollView.smoothScrollTo(0, scrollTo);
more to the answer from @jerry-sha
fun NestedScrollView.smoothScrollTo(view: View) {
var distance = view.top
var viewParent = view.parent
//traverses 10 times
for (i in 0..9) {
if ((viewParent as View) === this) break
distance += (viewParent as View).top
viewParent = viewParent.getParent()
}
smoothScrollTo(0, distance)
}