Android通知中.setContentTitle与自定义视图是否互斥?
Android自定义通知视图后标题不显示的解决方案
当使用setCustomContentView或setContent替换通知的内容视图时,系统会完全覆盖默认的通知内容区域——包括原生的标题、内容文本布局,因此通过setContentTitle设置的标题不会被渲染,默认会显示应用名称,这是正常的系统行为。
可行解决方案
方案1:使用自定义大视图保留原生折叠态标题
如果不需要在折叠状态下显示自定义内容,仅在展开时展示自定义视图,可以使用setCustomBigContentView替代setCustomContentView,这样折叠状态下会正常显示setContentTitle和setSubText的内容,展开后切换为自定义视图:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("foo") .setSubText("bar") // 设置展开后的自定义视图 .setCustomBigContentView(customNotificationView) // 保留系统装饰元素(应用图标、时间等) .setStyle(new NotificationCompat.DecoratedCustomViewStyle());
方案2:在自定义视图中模拟原生标题样式
如果必须在折叠状态下显示自定义内容,只能在自定义的RemoteViews布局中添加标题控件,手动设置标题内容,并匹配原生通知的标题样式:
- 自定义布局示例(
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:orientation="vertical" android:padding="16dp"> <!-- 模拟原生标题 --> <TextView android:id="@+id/tv_notification_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="16sp" android:textColor="@android:color/black" android:fontFamily="sans-serif-medium"/> <!-- 子文本 --> <TextView android:id="@+id/tv_notification_subtext" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="@android:color/darker_gray" android:layout_marginTop="4dp"/> <!-- 自定义内容区域 --> <View android:layout_width="match_parent" android:layout_height="60dp" android:background="@color/teal_200" android:layout_marginTop="8dp"/> </LinearLayout>
- 代码中设置自定义视图内容:
RemoteViews customNotificationView = new RemoteViews(getPackageName(), R.layout.custom_notification); // 设置标题 customNotificationView.setTextViewText(R.id.tv_notification_title, "foo"); // 设置子文本 customNotificationView.setTextViewText(R.id.tv_notification_subtext, "bar"); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setCustomContentView(customNotificationView) .setStyle(new NotificationCompat.DecoratedCustomViewStyle());
关于DecoratedCustomViewStyle的说明
该样式仅用于保留通知的系统装饰元素(如左侧应用图标、右上角时间与设置按钮),并不会保留原生的标题栏布局,因此即使添加该样式,setContentTitle的内容仍不会在自定义内容视图中显示。
内容的提问来源于stack exchange,提问作者Samuel Cochrane
相关产品推荐
相关产品推荐

