Android中如何修改通知背景颜色?已尝试代码仅更改标题和图标颜色
嘿,我来帮你搞定这个Android通知颜色的问题!
你当前用的setColorized(true)和setColor()其实是用来设置通知的强调色的——它只会改变通知图标、标题文字,以及部分系统里通知侧边的彩色竖条的颜色,这就是为什么你看到只有标题和图标变色的原因。下面分两种需求给你对应的解决方案:
需求1:让强调色完全生效(确保图标、标题、侧边条都变色)
如果你的问题是强调色没有完全生效(比如侧边条没显示设置的颜色),那得检查这几点:
- 对于Android 8.0(API 26)及以上的设备,必须创建通知渠道,且渠道的重要性要设为
IMPORTANCE_DEFAULT或更高(低重要性的通知会被系统限制颜色显示)。 - 不要在渠道配置里覆盖了颜色相关的设置。
给你完整的代码示例:
首先创建通知渠道(仅API 26+需要):
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( NOTIFICATION_CHANNEL_ID, "我的通知渠道", NotificationManager.IMPORTANCE_DEFAULT // 必须是DEFAULT或更高等级 ).apply { description = "用于展示自定义颜色的通知" enableLights(true) lightColor = Color.parseColor("#f7da64") // 可选,设置通知呼吸灯颜色 } val notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) }
然后构建通知:
val notification = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification_icon) // 必须设置小图标,否则通知无法显示 .setContentTitle("这是通知标题") .setContentText("这是通知内容") .setColorized(true) // 开启颜色化功能 .setColor(Color.parseColor("#f7da64")) // 设置强调色 .setPriority(NotificationCompat.PRIORITY_DEFAULT) .build()
需求2:修改整个通知的背景色
如果你的目标是把整个通知的背景都改成指定颜色,那系统默认的通知样式是不支持直接修改的,你需要用自定义通知布局来实现:
步骤1:创建自定义布局文件
在res/layout下新建custom_notification_layout.xml,设置你想要的背景色和文字样式:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#f7da64" <!-- 这里设置通知背景色 --> android:padding="16dp" android:orientation="vertical"> <TextView android:id="@+id/tv_notification_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:textColor="#000000" <!-- 标题文字颜色 --> android:text="自定义通知标题"/> <TextView android:id="@+id/tv_notification_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="#333333" <!-- 内容文字颜色 --> android:text="自定义通知内容"/> </LinearLayout>
步骤2:在代码中加载自定义布局并构建通知
// 初始化RemoteViews加载自定义布局 val remoteViews = RemoteViews(mContext.packageName, R.layout.custom_notification_layout) // 动态设置标题和内容(可选,也可以在布局里写死) remoteViews.setTextViewText(R.id.tv_notification_title, "你的自定义标题") remoteViews.setTextViewText(R.id.tv_notification_content, "你的自定义内容") val notification = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification_icon) // 必须设置小图标,否则通知不显示 .setCustomContentView(remoteViews) // 设置自定义布局 .setPriority(NotificationCompat.PRIORITY_DEFAULT) .build()
注意:自定义布局时要尽量适配不同屏幕尺寸,避免布局错乱;另外部分厂商的ROM可能会对自定义通知有样式限制,建议多测试几款设备~
内容的提问来源于stack exchange,提问作者yigitserin




