Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smoothy scroll to Child in NestedScrollView

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?

like image 506
Near1999 Avatar asked Nov 04 '15 12:11

Near1999


People also ask

How do I prevent NestedScrollView from scrolling if body is small?

The problem can be solved by moving the SliverAppBar into the CustomScrollView and not use the NestedScrollView at all.

How do I scroll to top programmatically?

scrollTo(0, 0); to scroll to the top of the NestedScrollView . You are welcome. This is more generally applied to both ScrollView or NestedScrollView.

What is difference between nested ScrollView and 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.


2 Answers

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)
}
like image 37
CHAN Avatar answered Sep 20 '22 18:09

CHAN


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);
like image 64
Near1999 Avatar answered Sep 16 '22 18:09

Near1999