折叠工具栏折叠和展开时状态栏颜色发生变化

问题描述 投票:0回答:1

我有一个要求,比如当折叠的工具栏展开时,状态栏颜色应该是透明的,当工具栏折叠时,状态栏应该获得主题颜色。与状态栏颜色相关的有很多,但这个要求是完全不同的。如果有人知道解决方案请帮忙。

android android-collapsingtoolbarlayout android-statusbar
1个回答
0
投票

您的 AppBar 有一个名为

.addOnOffsetChangedListener()
的侦听器。

使用此侦听器将为您提供一种更简单的滚动方法。

您可以使用偏移量来计算用户滚动是否等于侦听器提供的

verticalOffset

如果

offset
0
,则用户没有向下滚动屏幕,并且 AppBar 必须 展开。

如果

offset
not 0
,则用户必须已经向下滚动屏幕。

您可以按照此实施:

// 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)
    }
})

您可以从文档中找到有关

AppBarLayout

的更多信息
© www.soinside.com 2019 - 2024. All rights reserved.