I have expandable views inside CardView
thats parent is NestedScrollView
. I'm trying to create smooth scroll to child when expand animation ended. But I found only one solution:
scrollView.requestChildFocus(someView, someView);
This code works fine, but, when call requestChildFocus
it scrolls immediately, and that annoying me a little bit. Is it possible to scroll to child smoothly?
The problem can be solved by moving the SliverAppBar into the CustomScrollView and not use the NestedScrollView at all.
scrollTo(0, 0); to scroll to the top of the NestedScrollView . You are welcome. This is more generally applied to both ScrollView or NestedScrollView.
Nested scrolling is enabled by default. Show activity on this post. NestedScrollView is just like ScrollView, but in NestedScrollView we can put other scrolling views as child of it, e.g. RecyclerView. But if we put RecyclerView inside NestedScrollView, RecyclerView's smooth scrolling is disturbed.
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)
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With