如何移除Android自定义通知的头部信息及展开图标,实现全自定义布局
实现完全自定义的全宽高通知(隐藏系统头部元素)
要实现无系统默认头部(小图标、应用名、时间、展开箭头)的全宽高自定义通知,需要针对Android系统的强制要求和不同版本特性做适配,具体方案如下:
1. 准备透明小图标
Android系统要求所有通知必须设置小图标,否则会拒绝显示。我们可以创建一个全透明的图标来满足要求,同时视觉上隐藏它:
在res/drawable下创建transparent_icon.xml:
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> <path android:fillColor="@android:color/transparent" android:pathData="M0,0h24v24H0z"/> </vector>
2. 修改通知构建代码
调整原有的createNotification方法,隐藏系统默认元素并配置自定义视图:
private void createNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL); Intent i = new Intent(this, MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); builder.setContentIntent(intent); // 用透明图标满足系统强制要求,同时隐藏视觉显示 builder.setSmallIcon(R.drawable.transparent_icon); builder.setAutoCancel(true); // 隐藏所有系统默认文本和元素 builder.setShowWhen(false); // 隐藏时间 builder.setContentTitle(""); // 清空默认标题 builder.setContentText(""); // 清空默认内容 builder.setSubText(""); // 清空子文本 builder.setLargeIcon(null); // 移除大图标 // Android 11+ 隐藏展开箭头 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { builder.setShowExpandable(false); } RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification); final String time = DateFormat.getTimeInstance().format(new Date()).toString(); final String text = getResources().getString(R.string.collapsed, time); contentView.setTextViewText(R.id.textView, text); // 设置折叠状态的自定义视图 builder.setCustomContentView(contentView); // 配置展开状态的自定义视图(Android 4.1+) if (Build.VERSION.SDK_INT >= 16) { RemoteViews expandedView = new RemoteViews(getPackageName(), R.layout.notification_expanded); builder.setCustomBigContentView(expandedView); // Android 7.0+ 让通知默认展开 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { builder.setPriority(NotificationCompat.PRIORITY_HIGH); } } Notification notification = builder.build(); NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.notify(0, notification); }
3. 调整自定义布局
确保自定义布局的根元素占满宽度,且无多余内边距,示例res/layout/notification.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="#FF4081" android:orientation="vertical" android:padding="8dp"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textSize="18sp"/> </LinearLayout>
注意事项
- 系统通知高度限制:折叠状态下通知高度通常不超过64dp,展开状态可设置更高,但不同厂商ROM可能有额外限制。
- 定制ROM兼容:部分厂商(如小米、华为)可能强制显示应用名称或通知栏装饰元素,这类情况无法完全消除,只能尽量适配。
- 必须保留小图标:即使是透明图标,也不能省略
setSmallIcon调用,否则通知会被系统拦截不显示。
内容的提问来源于stack exchange,提问作者koder
相关产品推荐
相关产品推荐

