例如,Android 的 Google 应用程序有一个显示当地天气的通知。如果您在通知上向左滑动,它会显示一个“时钟图标”-动作(例如贪睡),如下所示。
如果单击时钟,将打开以下下拉菜单:
这是android系统的一个特性,我想在我的应用程序中实现。它应该通过通知操作打开,我想设置自定义选项,并且需要获取所选值。
有谁知道如何实施?
例如,Android 的 Google 应用程序有一个显示当地天气的通知。如果您在通知上向左滑动,它会显示一个“时钟图标”-动作(例如贪睡),如下所示。
如果单击时钟,将打开以下下拉菜单:
这是android系统的一个特性,我想在我的应用程序中实现。它应该通过通知操作打开,我想设置自定义选项,并且需要获取所选值。
有谁知道如何实施?
扩展功能由 Android 系统针对不同的通知样式提供。您需要一个显示用户可以从中选择的选项列表的视图。因此,您需要创建一个自定义视图并使用您的选项填充它。
您可以使用Notification.DecoratedCustomViewStyle()
Android 通知系统提供的自定义视图。
如果您想要折叠和展开视图的不同外观,那么您可以使用以下方法来设置它们 -
setStyle(new Notification.DecoratedCustomViewStyle())
.setCustomContentView(remoteViews)
.setCustomBigContentView(bigRemoteView);
您需要为布局中指定的所有选项添加不同的待处理意图。
例如 -
RemoteViews firstOption = ....;
Intent firstOptionIntent = // add some argument in this intent which depicts this option
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, flags);
setOnClickPendingIntent(R.id.<option_layout_id>, pendingIntent);
// 其他选项类似
RemoteViews secondOption = ....;
要在通知操作单击时添加下拉列表,您需要使用 2 种不同的布局,一种用于折叠视图,一种用于展开视图 -
Notification customNotification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout) // collapsed view layout
.setCustomBigContentView(notificationLayoutExpanded) // expanded view layout
.build();
这是标准的,适用于来自 Android oreo 的所有通知。
对于所有通知,您都可以使用此选项进行打盹。如果你想为旧的 Android 设备实现同样的 ui,你可以直接查看 Android oreo System UI 的源代码,从中我们可以得到 Android 8 及更高版本中的贪睡选项。
检查此字符串的使用
<!-- Notification: Snooze panel: message indicating how long the notification was snoozed for. [CHAR LIMIT=100]-->
1520 <string name="snoozed_for_time">Snoozed for <xliff:g id="time_amount" example="15 minutes">%1$s</xliff:g></string>
http://androidxref.com/8.1.0_r33/xref/frameworks/base/packages/SystemUI/res/values/strings.xml#1519