创建自定义大通知

时间:2014-01-20 15:14:09

标签: android android-layout android-notifications

我想创建一个包含一些控件的通知。由于文本和控件很小,默认通知大小(64dp),我希望它大于默认大小 可以创建更大的通知,我认为也可以有自定义布局,但我不知道如何。

更具体地说,以下屏幕截图显示了spotify的通知(图片来自here):Spotify notification

如您所见,尺寸大于默认尺寸。此外,它有一些没有文本的ImageButtons - 如果你使用Notification.Builder.addAction(),你可以提供一个图标,但也需要提供一个CharSequence作为描述 - 如果你把描述留空,仍然会留有空间用于文本,如果你传递 null ,它将崩溃。

有人能告诉我如何使用自定义布局创建大型通知吗?

由于

2 个答案:

答案 0 :(得分:56)

由于API更改而更新:

从API 24开始,Notification.Builder包含setCustomBigContentView(RemoteViews) - 方法。此外,NotificationCompat.Builder(它是support.v4包的一部分)包含此方法 请注意,NotificationCompat.Builder.setCustomBigContentView的文档说明:

  

使用自定义RemoteView代替扩展表单中的平台模板。这将覆盖此Builder对象将构造的扩展布局。在JELLY_BEAN之前的版本上没有操作。

因此,这也适用于API> = 16(JELLY_BEAN)。


原始答案

因此,在谷歌过度使用后,我发现this tutorial解释了如何使用自定义大布局。诀窍不是使用setStyle(),而是在构建后bigContentView 手动设置Notification字段。看起来有点hacky,但这是我最终提出的:

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&gt; = 16.我在这个答案中没有提到它,但是在上面给出的链接教程中提到了它:

  

扩展通知最初是在Android 4.1 JellyBean [API 16]中引入的。

答案 1 :(得分:2)

enter image description here 使用Kotlin进行自定义通知
             dialog_custom_notification                                          

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_margin="@dimen/dp_10"
                        android:background="@drawable/shape_bg_main_notification"
                        android:gravity="center"
                        android:orientation="horizontal"
                        android:padding="@dimen/dp_10">

                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="top">

                            <ImageView
                                android:id="@+id/ivAppIcon"
                                android:layout_width="@dimen/dp_36"
                                android:layout_height="@dimen/dp_36"
                                android:layout_gravity="top"
                                android:background="@mipmap/ic_launcher" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="top"
                            android:layout_marginLeft="@dimen/dp_10"
                            android:layout_weight="1"
                            android:orientation="vertical">

                            <TextView
                                android:id="@+id/tvNotificationTitle"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Notification Tile"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tvNotificationDescription"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginTop="@dimen/dp_5"
                                android:text="Notification Description" />

                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="top">

                            <TextView
                                android:id="@+id/tvDateTime"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_alignParentRight="true"
                                android:layout_gravity="top"
                                android:text="09:50" />
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>

        shape_bg_main_notification
        <?xml version="1.0" encoding="utf-8"?>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
            <solid android:color="@color/white" />

            <corners android:radius="@dimen/dp_6" />

        </shape>



        @SuppressLint("WrongConstant")
                    fun showOfflineNotification(context: Context, title: String, description: String) {
                        val NOTIFICATION_CHANNEL_ID = "com.myapp"
                        val intent = Intent(context, HomeActivity::class.java)
                        intent.putExtra("notification", 1)
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        if (intent != null) {
                            val pendingIntent = PendingIntent.getActivity(
                                context, getTwoDigitRandomNo(), intent,
                                PendingIntent.FLAG_ONE_SHOT
                            )
                            val defaultSoundUri =
                                RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

                            val remoteCollapsedViews = RemoteViews(packageName, R.layout.dialog_custom_notification)
                            remoteCollapsedViews.setTextViewText(R.id.tvNotificationTitle, title)
                            remoteCollapsedViews.setTextViewText(R.id.tvNotificationDescription, description)
                            remoteCollapsedViews.setTextViewText(R.id.tvDateTime, getTime())

                            val notificationBuilder = NotificationCompat.Builder(context)
                            notificationBuilder.setCustomBigContentView(remoteCollapsedViews)
                            notificationBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
                            notificationBuilder.setLargeIcon(
                                BitmapFactory.de

        codeResource(
                                        context.resources,
                                        R.mipmap.ic_launcher
                                    )
                                )
                                notificationBuilder.setBadgeIconType(R.mipmap.ic_launcher_round)
                                notificationBuilder.setContentTitle(title)
                                if (description != null) {
                                    notificationBuilder.setContentText(description)
                                    notificationBuilder.setStyle(
                                        NotificationCompat.BigTextStyle().bigText(description)
                                    )
                                }
                                notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH)
                                notificationBuilder.setAutoCancel(true)
                                notificationBuilder.setSound(defaultSoundUri)
                                notificationBuilder.setVibrate(longArrayOf(1000, 1000))
                                notificationBuilder.setContentIntent(pendingIntent)

                                val notificationManager =
                                    context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    val importance = NotificationManager.IMPORTANCE_MAX
                                    val notificationChannel = NotificationChannel(
                                        NOTIFICATION_CHANNEL_ID,
                                        "NOTIFICATION_CHANNEL_NAME",
                                        importance
                                    )
                                    notificationChannel.enableLights(true)
                                    notificationChannel.lightColor = Color.RED
                                    notificationChannel.enableVibration(true)
                                    notificationChannel.vibrationPattern = longArrayOf(1000, 1000)
                                    assert(notificationManager != null)
                                    notificationBuilder.setChannelId(NOTIFICATION_CHANNEL_ID)
                                    notificationManager.createNotificationChannel(notificationChannel)
                                }
                                notificationManager.notify(
                                    getTwoDigitRandomNo()/*Id of Notification*/,
                                    notificationBuilder.build()
                                )
                            }
                        }

                        private fun getTime(): String {
                            val calendar = Calendar.getInstance()
                            val mdformat = SimpleDateFormat("HH:mm")
                            val strDate = mdformat.format(calendar.time)
                            return strDate
                        }

                        fun getTwoDigitRandomNo(): Int {
                            return Random().nextInt(90) + 10
                        }



      [1]: https://me.stack.imgur.com/rQFP8.png


  [1]: https://me.stack.imgur.com/fKM9C.png