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

如何判断系统导航类型(手势/2-3键导航)并设置对应背景色?

判断系统导航类型并设置对应导航栏背景色

步骤1:实现导航类型判断函数

先添加工具函数,用于获取当前设备的系统导航模式:

import android.content.Context
import android.provider.Settings

fun getCurrentNavigationMode(context: Context): Int {
    return Settings.Secure.getInt(
        context.contentResolver,
        Settings.Secure.NAVIGATION_MODE,
        Settings.Secure.NAVIGATION_MODE_UNDEFINED
    )
}

步骤2:在Compose中根据导航模式设置背景色

修改你提供的Compose代码,加入导航类型判断逻辑,针对不同模式设置对应的导航栏颜色:

import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
import android.app.Activity
import android.graphics.Color
import android.provider.Settings

@Composable
fun SetupSystemBars(darkTheme: Boolean = isSystemInDarkTheme()) {
    val view = LocalView.current
    val window = (view.context as Activity).window

    if (!view.isInEditMode) {
        SideEffect {
            window.statusBarColor = Color.Transparent.toArgb()
            
            // 获取当前导航模式
            val navigationMode = getCurrentNavigationMode(view.context)
            
            // 根据导航模式设置导航栏背景色
            window.navigationBarColor = when (navigationMode) {
                Settings.Secure.NAVIGATION_MODE_GESTURAL -> {
                    // 手势导航:自定义颜色,示例为半透明黑色
                    Color(0x80000000).toArgb()
                }
                Settings.Secure.NAVIGATION_MODE_3_BUTTONS,
                Settings.Secure.NAVIGATION_MODE_2_BUTTONS -> {
                    // 2键/3键导航:自定义颜色,示例为灰色
                    Color.GRAY.toArgb()
                }
                else -> {
                    // 默认 fallback 颜色
                    Color.Transparent.toArgb()
                }
            }

            WindowCompat.getInsetsController(window, view).apply {
                isAppearanceLightStatusBars = !darkTheme
                isAppearanceLightNavigationBars = !darkTheme
            }
        }
    }
}

// 工具函数:获取当前导航模式
fun getCurrentNavigationMode(context: Context): Int {
    return Settings.Secure.getInt(
        context.contentResolver,
        Settings.Secure.NAVIGATION_MODE,
        Settings.Secure.NAVIGATION_MODE_UNDEFINED
    )
}

模式说明

  • NAVIGATION_MODE_GESTURAL:对应全手势导航模式
  • NAVIGATION_MODE_2_BUTTONS:对应返回+主页的2键导航
  • NAVIGATION_MODE_3_BUTTONS:对应返回+主页+多任务的3键导航
  • 你可以直接替换每种模式下的Color值,适配项目的主题需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:20:35