我想创建一个包含一些控件的通知。由于文本和控件很小,默认通知大小为(64dp),因此我希望它大于默认大小。
可以创建更大的通知,我认为也可以具有自定义布局,但是我不知道如何。
更具体地说,以下屏幕截图显示了来自spotify的通知(图像来自此处):
如您所见,大小大于默认值。此外,它具有某种不带文本的ImageButtons-如果您使用Notification.Builder.addAction(),则可以提供一个图标,但还需要提供CharSequence作为描述-如果将描述保留为空,则仍然会有空格为文本保留,如果您传递null,它将崩溃。
有人可以告诉我如何使用自定义布局创建大型通知吗?
谢谢
由于API更改而进行的更新:
从API 24开始,Notification.Builder
包含一个setCustomBigContentView(RemoteViews)方法。另外,NotificationCompat.Builder(属于support.v4软件包的一部分)也包含此方法。
请注意,NotificationCompat.Builder.setCustomBigContentView的文档指出:
提供自定义的RemoteView,以代替展开形式的平台模板使用。这将覆盖此Builder对象否则将构造的扩展布局。JELLY_BEAN之前的版本无操作。
因此,这也仅适用于API> = 16(JELLY_BEAN)。
原始答案
因此,在Google过度使用之后,我发现本教程解释了如何使用自定义的大布局。诀窍是不使用它,setStyle()
而是在构建它后手动设置它的bigContentView
字段。似乎有点骇人听闻,但这就是我最终想到的:Notification
notification_layout_big.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="100dp" <!-- This is where I manually define the height -->
android:orientation="horizontal" >
<!-- some more elements.. -->
</LinearLayout>
Notification
用代码构建:
Notification foregroundNote;
RemoteViews bigView = new RemoteViews(getApplicationContext().getPackageName(),
R.layout.notification_layout_big);
// bigView.setOnClickPendingIntent() etc..
Notification.Builder mNotifyBuilder = new Notification.Builder(this);
foregroundNote = mNotifyBuilder.setContentTitle("some string")
.setContentText("Slide down on note to expand")
.setSmallIcon(R.drawable.ic_stat_notify_white)
.setLargeIcon(bigIcon)
.build();
foregroundNote.bigContentView = bigView;
// now show notification..
NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyManager.notify(1, foregroundNote);
编辑
正如chx101所指出的,这仅适用于API> =16。我没有在此答案中提及它,但在上面给定的链接教程中提到了它:
扩展的通知最初是在Android 4.1 JellyBean [API 16]中引入的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句