如何修改APK头部颜色及实现导航栏随应用颜色自动变色
一、修改APK头部(ActionBar/Toolbar)颜色
针对原生ActionBar
在res/values/styles.xml中找到应用主题(通常为AppTheme),添加或修改colorPrimary属性:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- 其他主题属性 --> <item name="colorPrimary">@color/your_target_color</item> </style>
colorPrimary的取值直接对应ActionBar的背景色,替换your_target_color为你定义的颜色值即可。
针对自定义Toolbar
如果使用了布局内的自定义Toolbar控件,有两种修改方式:
- 布局文件中直接设置背景:
<androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/your_target_color"/>
- 代码中动态配置:
Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.your_target_color));
二、实现导航栏颜色随应用主体色自动变化
场景1:系统底部导航栏(系统UI)
静态跟随主题
在res/values/styles.xml的主题中绑定navigationBarColor到主体色:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- 其他主题属性 --> <item name="navigationBarColor">?attr/colorPrimary</item> </style>
此时导航栏会自动跟随colorPrimary的变化同步更新。
运行时动态切换
当应用主体色在运行中改变时,调用以下代码更新导航栏颜色:
// currentColorResId 为当前主体色的资源ID getWindow().setNavigationBarColor(ContextCompat.getColor(this, currentColorResId));
可在主题切换事件、页面跳转回调等场景中触发该代码。
场景2:应用内自定义底部导航栏(如BottomNavigationView)
动态修改导航栏背景色即可实现同步:
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav); // currentColorResId 为当前主体色的资源ID bottomNav.setBackgroundColor(ContextCompat.getColor(this, currentColorResId));
若需同步图标/文字颜色,可定义颜色状态列表(res/color/bottom_nav_item_color.xml):
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/selected_color" android:state_selected="true"/> <item android:color="@color/unselected_color"/> </selector>
再通过代码绑定:
bottomNav.setItemIconTintList(ContextCompat.getColorStateList(this, R.color.bottom_nav_item_color)); bottomNav.setItemTextColor(ContextCompat.getColorStateList(this, R.color.bottom_nav_item_color));
内容的提问来源于stack exchange,提问作者Carloesposito98
相关产品推荐
相关产品推荐

