Android 7及以上通知文字颜色与背景修改方案咨询
嘿,你选对路子了!DecoratedCustomViewStyle完美匹配你的需求——既能自定义通知主体的背景和文字颜色,又能完整保留系统自带的通知头部、操作按钮,甚至折叠/展开的原生布局逻辑。下面给你一套极简的实现步骤,直接就能跑起来:
第一步:创建自定义通知布局
先在res/layout下新建custom_notification.xml,这里可以自由设置背景(颜色或Drawable)和文字颜色:
<!-- res/layout/custom_notification.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/light_gray" <!-- 浅色背景,也可以用@drawable/your_custom_bg --> android:padding="16dp" android:orientation="vertical"> <TextView android:id="@+id/tv_notif_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/dark_blue" <!-- 自定义标题文字颜色 --> android:textSize="18sp" android:textStyle="bold"/> <TextView android:id="@+id/tv_notif_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/dark_gray" <!-- 自定义内容文字颜色 --> android:textSize="14sp" android:layout_marginTop="8dp"/> </LinearLayout>
要是想用Drawable做背景,比如带圆角的浅色背景,可以新建res/drawable/notification_bg.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#F8F9FA"/> <!-- 浅灰蓝背景 --> <corners android:radius="12dp"/> <!-- 圆角效果 --> </shape>
然后把布局里的android:background改成@drawable/notification_bg就行。
第二步:构建并发送通知
用NotificationCompat.Builder结合DecoratedCustomViewStyle来实现,Kotlin代码示例如下:
// 获取通知管理器 val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Android 8.0+ 必须创建通知渠道 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( "custom_notif_channel_id", "自定义通知渠道", NotificationManager.IMPORTANCE_DEFAULT ).apply { description = "展示自定义样式的通知" } notificationManager.createNotificationChannel(channel) } // 加载自定义布局到RemoteViews val customRemoteView = RemoteViews(packageName, R.layout.custom_notification) customRemoteView.setTextViewText(R.id.tv_notif_title, "我的自定义通知") customRemoteView.setTextViewText(R.id.tv_notif_content, "背景和文字颜色都是我自己设的,系统头部和按钮还在哦~") // 构建通知 val notification = NotificationCompat.Builder(this, "custom_notif_channel_id") .setSmallIcon(R.drawable.ic_notification) // 注意:必须设置小图标,否则通知不显示 .setStyle(NotificationCompat.DecoratedCustomViewStyle()) // 核心:启用系统装饰保留模式 .setCustomContentView(customRemoteView) // 设置折叠状态的自定义视图 .setCustomBigContentView(customRemoteView) // 可选:展开状态用同一布局(也可以单独做一个) // 保留系统操作按钮示例 .addAction(R.drawable.ic_share, "分享", sharePendingIntent) .addAction(R.drawable.ic_save, "保存", savePendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .build() // 发送通知 notificationManager.notify(1001, notification)
几个关键注意事项
- 必须设置小图标:Android要求所有通知都要有
setSmallIcon,否则会直接不显示通知。 - 区分折叠/展开布局:如果需要折叠和展开状态显示不同的自定义布局,分别给
setCustomContentView和setCustomBigContentView传入不同的RemoteViews即可。 - 可读性优先:文字颜色要和背景形成足够对比度,比如浅色背景配深色文字,避免和系统头部的文字混淆。
内容的提问来源于stack exchange,提问作者Daniele B




