// Your appbar, findViewById<AppBarLayout>(R.id....) should be used or binding
// You have to use your layout view and not initializing like this
val appbar = AppBarLayout(this)
// Variable to store when the appbar is collapsed or expanded
var isExpanded = false
// Variable to store the total scroll range
var scrollRange = -1
// Add a listener for the offset
appbar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
// If the scrollRange has not been initialized
if (scrollRange == -1) {
// Set to the total scroll range
scrollRange = appBarLayout.totalScrollRange
}
// If the scroll range + the verticalOffset == 0
// If the sum result is 0 the appbar is expanded
// If not, it must be collapsed
if (scrollRange + verticalOffset == 0) {
// The appbar is expanded
isExpanded = true
// Set the statusBar color when the appbar is expanded
window.statusBarColor = getColor(R.color.red)
// If the sum result is not 0 and it was previously expanded
// Now it must be collapsed
} else if (isExpanded) {
// The appbar is collapsed
isExpanded = false
// Set the statusBar color when the appbar is collapsed
window.statusBarColor = getColor(R.color.blue)
}
})
1条答案
按热度按时间siv3szwd1#
您的
AppBar
有一个名为.addOnOffsetChangedListener()
的侦听器。使用此侦听器将为您提供一种更简单的方法,同时使用屏幕滚动。
您可以使用偏移量来计算用户滚动是否等于侦听器提供的
verticalOffset
。如果
offset
是0
,则用户没有向下滚动屏幕,AppBar必须展开。如果
offset
是not 0
(负数),则用户必须向下滚动屏幕。您可以遵循此实现:
字符串
您可以在documentation中找到有关
AppBarLayout
的更多信息