Mal*_*aKa 19 android android-layout android-notifications
我想创建一个包含一些控件的通知.由于文本和控件很小,默认通知大小(64dp),我希望它大于默认大小.
可以创建更大的通知,我认为也可以有自定义布局,但我不知道如何.
更具体地说,以下屏幕截图显示了spotify的通知(图片取自此处):
如您所见,尺寸大于默认值.此外,它有一些没有文本的ImageButtons - 如果你使用Notification.Builder.addAction(),你可以提供一个图标,但也需要提供一个CharSequence作为描述 - 如果你把描述留空,仍然会有空间为文本保留,如果传递null,它将崩溃.
任何人都可以告诉我如何使用自定义布局创建大型通知吗?
谢谢
Mal*_*aKa 58
API更改导致的更新:
从API 24开始,它Notification.Builder包含一个setCustomBigContentView(RemoteViews) -method.还NotificationCompat.Builder(这是support.v4包的一部分)包含此方法.
请注意,NotificationCompat.Builder.setCustomBigContentView的文档指出:
提供自定义RemoteView以代替扩展形式的平台模板.这将覆盖此Builder对象将构造的扩展布局.在JELLY_BEAN之前的版本上没有操作.
因此,这也仅适用于API> = 16(JELLY_BEAN).
原始答案
因此,在谷歌过度使用后,我发现本教程解释了如何使用自定义大布局.诀窍是不使用,setStyle()而是手动设置构建它后的bigContentView字段.看起来有点hacky,但这是我最终提出的: 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>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
编辑
如chx101所述,这仅适用于API> = 16.我在这个答案中没有提到它,但在上面给出的链接教程中提到了它:
扩展通知最初是在Android 4.1 JellyBean [API 16]中引入的.
| 归档时间: |
|
| 查看次数: |
35304 次 |
| 最近记录: |