Last active
August 26, 2020 16:15
-
-
Save yasukotelin/0b040a0e2954fd4176ba11f954b55837 to your computer and use it in GitHub Desktop.
FAB in CoordinatorLayoutでスクロール時にShow/HideするBehavior
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.util.AttributeSet | |
import android.view.View | |
import androidx.coordinatorlayout.widget.CoordinatorLayout | |
import androidx.core.view.ViewCompat | |
import com.google.android.material.floatingactionbutton.FloatingActionButton | |
class ScrollAwareBehavior(context: Context?, attrs: AttributeSet?) : | |
FloatingActionButton.Behavior(context, attrs) { | |
override fun onStartNestedScroll( | |
coordinatorLayout: CoordinatorLayout, | |
child: FloatingActionButton, | |
directTargetChild: View, | |
target: View, | |
axes: Int, | |
type: Int | |
): Boolean { | |
// Ensure we react to vertical scrolling | |
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, | |
consumed: IntArray | |
) { | |
super.onNestedScroll( | |
coordinatorLayout, | |
child, | |
target, | |
dxConsumed, | |
dyConsumed, | |
dxUnconsumed, | |
dyUnconsumed, | |
type, | |
consumed | |
) | |
if (dyConsumed > 0 && child.visibility == View.VISIBLE) { | |
// User scrolled down and the FAB is currently visible -> hide the FAB | |
child.hide() | |
} else if (dyConsumed < 0 && child.visibility != View.VISIBLE) { | |
// User scrolled up and the FAB is currently not visible -> show the FAB | |
child.show() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment