如何判断系统导航类型(手势/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
相关产品推荐
相关产品推荐

