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

6ss1mwsb  于 2023-11-15  发布在  Android
关注(0)|答案(1)|浏览(124)

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

siv3szwd

siv3szwd1#

您的AppBar有一个名为.addOnOffsetChangedListener()的侦听器。
使用此侦听器将为您提供一种更简单的方法,同时使用屏幕滚动。
您可以使用偏移量来计算用户滚动是否等于侦听器提供的verticalOffset
如果offset0,则用户没有向下滚动屏幕,AppBar必须展开。
如果offsetnot 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)
    }
})

字符串
您可以在documentation中找到有关AppBarLayout的更多信息

相关问题