ssuukk
ssuukk

Reputation: 8410

How do I pass scroll events from my View to CoordinatorLayout?

Material Design has this fancy pattern of scrolling/hiding/pinning parts of the ToolBar/ActionBar when some View below gets scrolled. I have my own, very specialized view, that isn't a descendant of RecyclerView (that probably handles this by default), so it doesn't work with scroll behaviors. I suspect I need to pass some scroll information up to Coordinator-layout to handle hide on scroll. But how do I do it?

Upvotes: 2

Views: 576

Answers (1)

kris larson
kris larson

Reputation: 30985

You will want to look at a support class called NestedScrollingChildHelper (docs).

You can easily graft this helper class onto your scrolling view. Have your class implement NestedScrollingChild, instantiate a delegate instance, then delegate all the interface methods to that instance.

Finally, whenever you are processing a scroll or a fling, you call these methods to see if the CoordinatorLayout will consume the motion events before you scroll your view.

Here's a piece of code from NestedScrollingChild.onTouchEvent() to show you nested scrolling in action:

            final int y = (int) MotionEventCompat.getY(ev, activePointerIndex);
            int deltaY = mLastMotionY - y;
            if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) {
                deltaY -= mScrollConsumed[1];
                vtev.offsetLocation(0, mScrollOffset[1]);
                mNestedYOffset += mScrollOffset[1];
            }

See line 766 of this file: NestedScrollView.java. BTW, this class uses the NestedScrollingChildHelper delegate, so you can see exactly how it all works.

Don't forget to use ViewCompat instead of View, ViewGroupCompat instead of ViewGroup, etc.

Upvotes: 2

Related Questions