【问题标题】:How to change background color of custom notification depending on day/night mode如何根据日/夜模式更改自定义通知的背景颜色
【发布时间】:2019-05-16 08:18:43
【问题描述】:

我们是一个从事学校作业的小组。我们创建了一个自定义通知,它工作正常。唯一的问题是我很难弄清楚如何根据它是处于白天还是夜间模式来使自定义通知更改背景颜色。

我用于创建通知的代码

Intent challengedIntent = new Intent(this, StartActivity.class); 
stackBuilder.addNextIntentWithParentStack(challengedIntent);
PendingIntent challengedPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);


RemoteViews views = new RemoteViews(getPackageName(), R.layout.notification);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.app_channel))
            .setSmallIcon(R.mipmap.carfight_launcher)
            .setCustomContentView(views)
            .setCustomBigContentView(views)
            .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
            .setContentIntent(challengedPendingIntent)
            .setColorized(true)
            .setColor(Color.parseColor("#ff0000"));

views.setImageViewResource(R.id.imagesVeiw_wins,R.drawable.ic_medal_solid);
views.setImageViewResource(R.id.imageVeiw_matches,R.drawable.ic_battle);


NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, builder.build());

如何更改它以在日/夜模式下做出反应?

minSDKVersion 为 16

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    其中一种方法是首先确定手机是否处于夜间模式。 这可以通过以下代码完成:

    int nightModeFlags =
        getContext().getResources().getConfiguration().uiMode &
        Configuration.UI_MODE_NIGHT_MASK;
    switch (nightModeFlags) {
        case Configuration.UI_MODE_NIGHT_YES:
             setupNightMode();
             break;
    
        case Configuration.UI_MODE_NIGHT_NO:
             setupDayMode();
             break;
    
        case Configuration.UI_MODE_NIGHT_UNDEFINED:
             doStuff();
             break;
    }
    

    然后,一旦您知道它是否处于夜间模式,只需相应地创建您的 RemoteView 对象。这意味着您必须有两种布局,一种用于普通模式,另一种用于夜间模式。 像这样的:

    RemoteView remoteView;
    
    //Switch case here
    
    setupNightMode(){
    remoteView = new RemoteView() //inflate night mode layout
    }
    
    
    setupDayMode()
    {
    remoteView = new RemoteView() //inflate day mode layout
    }
    

    最后: 在构建通知时使用 remoteView 对象:

    NotificationCompat.Builder builder = ...
    

    【讨论】:

    • 虽然这可行,但它对操作系统使用的背景颜色做出假设,这取决于操作系统。例如,AOSP Android 9 在深色主题中使用白色通知背景,而 AOSP Android 10 在深色主题中使用深色通知背景。更复杂的是,三星还在 Android 9 的深色主题中使用了深色通知背景。
    • @Sam 谢谢你的评论。是的,答案可能是对操作系统使用的颜色做出假设,但您似乎也假设开发人员对暗模式使用什么以及不使用什么缺乏常识。大声笑。
    猜你喜欢
    • 2021-09-03
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多