how to show/hide FAB on scroll Recycler view with coordinator parent

前端 未结 5 864
轻奢々
轻奢々 2021-02-04 11:41

I have an activity with coordinator layout.inside activity there is a fragment with Recycler view and float button.how can I show/hide float button when Scroll Recycler view and

5条回答
  •  情深已故
    2021-02-04 12:15

    Here is working solution:

    class HideOnScrollFabBehavior(context: Context?, attrs: AttributeSet?) : FloatingActionButton.Behavior() {
    
        // changes visibility from GONE to INVISIBLE when fab is hidden because
        // due to CoordinatorLayout.onStartNestedScroll() implementation
        // child view's (here, fab) onStartNestedScroll won't be called anymore
        // because it's visibility is GONE
        private val listener = object : FloatingActionButton.OnVisibilityChangedListener() {
            override fun onHidden(fab: FloatingActionButton?) {
                fab?.visibility = INVISIBLE
            }
        }
    
        override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, directTargetChild: View, target: View, axes: Int, type: Int): Boolean {
            return axes == ViewCompat.SCROLL_AXIS_VERTICAL // Ensure we react to vertical scrolling
                    || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type)
        }
    
        override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int, consumed: IntArray) {
            super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, consumed)
            if (!target.canScrollVertically(1) && dyConsumed > 0 && child.visibility == VISIBLE) {
                // hide the FAB when scroll view reached its bottom
                child.hide(listener)
            } else if (dyConsumed < 0 && child.visibility != VISIBLE) {
                // show the FAB on scroll up
                child.show()
            }
        }
    
    }
    

提交回复
热议问题