You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化天气App中基于时间切换背景与状态栏颜色的冗余代码?

优化时间驱动的样式切换逻辑

你当前的多分支if-else逻辑冗余度高、维护成本高,推荐用数据类封装样式+状态映射的方式简化代码,具体实现如下:

1. 定义样式数据类

先创建一个数据类,把每个时间段需要的背景Drawable和状态栏颜色资源ID打包为一个整体:

data class TimeTheme(
    val backgroundResId: Int,
    val statusBarColorResId: Int
)

2. 建立时间状态与样式的映射

用when表达式替换原有的多分支判断,清晰对应每个时间状态到对应的样式配置:

private fun getCurrentTimeTheme(): TimeTheme {
    return when {
        Time.isMidNight -> TimeTheme(R.drawable.midnight_gradient, R.color.midnight_end)
        Time.isSunrise -> TimeTheme(R.drawable.sunrise_gradient, R.color.sunrise_end)
        Time.isMorning -> TimeTheme(R.drawable.morning_gradient, R.color.morning_end)
        Time.isNoon -> TimeTheme(R.drawable.noon_gradient, R.color.noon_end)
        Time.isAfterNoon -> TimeTheme(R.drawable.afternoon_gradient, R.color.afternoon_end)
        Time.isSunset -> TimeTheme(R.drawable.sunset_gradient, R.color.sunrise_end)
        else -> TimeTheme(R.drawable.night_gradient, R.color.night_end)
    }
}

3. 简化样式切换函数

现在只需要获取当前主题配置,统一执行设置逻辑即可,代码冗余完全消除:

fun updateAppTheme() {
    Time.getTimeState()
    val window = this.window
    val currentTheme = getCurrentTimeTheme()
    
    binding.mainConstraint.background = ResourcesCompat.getDrawable(resources, currentTheme.backgroundResId, null)
    window.statusBarColor = ResourcesCompat.getColor(resources, currentTheme.statusBarColorResId, null)
}

优化优势

  • 冗余消除:重复的ResourcesCompat调用只保留一次,核心逻辑更聚焦
  • 易维护:新增时间段时,仅需在getCurrentTimeTheme()的when块中添加一行映射,无需修改设置逻辑
  • 可读性提升:数据类明确了样式的组成属性,状态映射关系一目了然

内容的提问来源于stack exchange,提问作者Ahmed Khaled

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:55:16