Android Hide Bottom FloatingActionButton On Scroll Down

NOTE: Sadly, there is not build-in feature by design library to achieve this behaviour (unless you are using collapingsing AppBarLayout with FloatingActionButton anchored to it).

One of the easier way is to listen RecyclerView.addOnScrollListener.

recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {    override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {        if (dy > 0)            fab.hide()        else if (dy < 0)            fab.show()    }})

Another slightly more complex solution is create a behaviour class which extends from FloatingActionButton.Behavior.

class ScrollAwareFABBehavior(context: Context, attrs: AttributeSet): FloatingActionButton.Behavior(context, attrs) {    override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout,                                     child: FloatingActionButton, directTargetChild: View, target: View,                                     axes: Int, type: Int): Boolean {        return axes == ViewCompat.SCROLL_AXIS_VERTICAL || 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) {        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,                dyUnconsumed, type)        if (dyConsumed > 0 && child.visibility == View.VISIBLE) {            child.hide(object : FloatingActionButton.OnVisibilityChangedListener() {                override fun onHidden(fab: FloatingActionButton) {                    super.onHidden(fab)                    fab.visibility = View.INVISIBLE                }            })        } else if (dyConsumed < 0 && child.visibility != View.VISIBLE) {            child.show()        }    }}

Apply the behaviour in FloatingActionButton.

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:layout_behavior="com.luasoftware.lualib2.ScrollAwareFABBehavior"
    app:tint="@android:color/white"
    app:srcCompat="@drawable/ic_photo_camera_black_24dp" />

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.