首页 > 解决方案 > 在 Android 中启用展开布局时如何默认显示自定义通知和折叠布局

问题描述

当用户折叠或展开通知时,我想通过支持大小布局作为上面的屏幕截图来显示我的自定义通知。但结果它默认显示扩展通知。我想默认将其显示为折叠通知,并且仅在用户展开通知时显示展开通知。

请检查我的代码如下:

 private fun initCustomNotification() {
    // Get the layouts to use in the custom notification
    val notificationLayout = RemoteViews(packageName, R.layout.custom_notification_small_layout)
    val notificationLayoutExpanded = RemoteViews(packageName, R.layout.custom_notification_large_layout)

    // Apply the layouts to the notification
    customNotificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.dog)
            .setStyle(NotificationCompat.DecoratedCustomViewStyle())
            .setCustomContentView(notificationLayout)
            .setCustomBigContentView(notificationLayoutExpanded)
            .setOngoing(true)
            .setShowWhen(false)
}

谢谢。

标签: androidlayoutkotlinnotificationsandroid-custom-view

解决方案


可能会晚,但可能对其他人有帮助。您可以默认设置折叠通知,NotificationManager.IMPORTANCE_MIN您可以默认设置扩展通知NotificationManager.IMPORTANCE_HIGH.

你可以有完整的例子:

public void generateCollepedNotification(Context context, String notificationTitle, String notificationSubText, String notificationMessage) {
        String channelId = "my_channel_id";
        int notification_id = 1001;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.mipmap.ic_logo_notification)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_logo)) // optional
                .setContentTitle(notificationTitle)
                .setContentText(notificationMessage)
                .setSubText(notificationSubText) // optional
                .setColor(ContextCompat.getColor(context, R.color.colorPrimary)) // optional
                .setAutoCancel(true);

        getNotificationManagerIMPORTANCE_MIN(context, channelId).notify(notification_id, builder.build());
    }



private NotificationManager getNotificationManagerIMPORTANCE_MIN(Context context, String channelId) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            String channelName = "My Channel Name";
            String channelDescription = "This is Description of my channel";
            NotificationChannel mChannel = new NotificationChannel(
                    channelId,
                    channelName,
                    NotificationManager.IMPORTANCE_MIN
            );
            mChannel.setDescription(channelDescription);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.setShowBadge(false);
            notificationManager.createNotificationChannel(mChannel);
        }
        return notificationManager;
    }

在此处输入图像描述


推荐阅读