Aqui está uma solução Kotlin . Adicione um OnOffsetChangedListener
ao AppBarLayout
.
Método A:
Adicione AppBarStateChangeListener.kt
ao seu projeto:
import com.google.android.material.appbar.AppBarLayout
import kotlin.math.abs
abstract class AppBarStateChangeListener : AppBarLayout.OnOffsetChangedListener {
enum class State {
EXPANDED, COLLAPSED, IDLE
}
private var mCurrentState = State.IDLE
override fun onOffsetChanged(appBarLayout: AppBarLayout, i: Int) {
if (i == 0 && mCurrentState != State.EXPANDED) {
onStateChanged(appBarLayout, State.EXPANDED)
mCurrentState = State.EXPANDED
}
else if (abs(i) >= appBarLayout.totalScrollRange && mCurrentState != State.COLLAPSED) {
onStateChanged(appBarLayout, State.COLLAPSED)
mCurrentState = State.COLLAPSED
}
else if (mCurrentState != State.IDLE) {
onStateChanged(appBarLayout, State.IDLE)
mCurrentState = State.IDLE
}
}
abstract fun onStateChanged(
appBarLayout: AppBarLayout?,
state: State?
)
}
Adicione o ouvinte ao seu appBarLayout
:
appBarLayout.addOnOffsetChangedListener(object: AppBarStateChangeListener() {
override fun onStateChanged(appBarLayout: AppBarLayout?, state: State?) {
Log.d("State", state.name)
when(state) {
State.COLLAPSED -> { /* Do something */ }
State.EXPANDED -> { /* Do something */ }
State.IDLE -> { /* Do something */ }
}
}
}
)
Método B:
appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
if (abs(verticalOffset) - appBarLayout.totalScrollRange == 0) {
// Collapsed
} else if (verticalOffset == 0) {
// Expanded
} else {
// Idle
}
}
)