Create a Custom Notification Layout
日付:2021/12/01
URL:https://developer.android.com/training/notify-user/custom-notification, https://speakerdeck.com/kobakei/kai-fa-zhe-gazhi-tuteokitaitong-zhi-falseli-shi
調査者:Mori Atsushi
カテゴリ:User Interface
一言で表すと
RemoteViewでゴリゴリカスタムすっぞ!というやつ
概要
code:kotlin
val notificationLayout = RemoteViews(packageName, R.layout.notification_small)
val notificationLayoutExpanded = RemoteViews(packageName, R.layout.notification_large)
val customNotification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(NotificationCompat.DecoratedCustomViewStyle()) // styleを指定
.setCustomContentView(notificationLayout) // 閉じられたときのレイアウト
.setCustomBigContentView(notificationLayoutExpanded) // 開かれたときのレイアウト
.build()
https://scrapbox.io/files/61a76b50ce94a60022b478b4.png
https://speakerdeck.com/kobakei/kai-fa-zhe-gazhi-tuteokitaitong-zhi-falseli-shi?slide=65
注意点
通知の背景色はデバイスやバージョンによって異なる
TextAppearance_Compat_Notification や TextAppearance_Compat_Notification_Title styleを使う
自動で適切な文字色を当ててくれる
code:kotlin
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/notification_title"
android:id="@+id/notification_title"
style="@style/TextAppearance.Compat.Notification.Title" />
カスタムレイアウトが様々なデバイスの向きと解像度で機能するように注意すること
setStyle を呼び出さないことで完全なカスタムレイアウトも作成できた
Android12からは Notification.DecoratedCustomViewStyle とほぼ同じ挙動になる
推奨されていないみたい
注: 装飾のない通知を使用することは、推奨されません。他の通知と釣り合わなくなるおそれがあります。また、デバイスに応じて、通知領域に適用されるスタイルも変わるため、通知に装飾がないと、レイアウトの互換性に関して重大な問題が生じるおそれがあります。
https://scrapbox.io/files/61a76cd799d4260022a4f9c1.png
https://speakerdeck.com/kobakei/kai-fa-zhe-gazhi-tuteokitaitong-zhi-falseli-shi?slide=59
その他のstyle
BigPictureStyle
大きな画像を表示する
https://developer.android.com/reference/androidx/core/app/NotificationCompat.BigPictureStyle
code:java
Notification notification = new Notification.Builder(mContext)
.setContentTitle("New photo from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_post)
.setLargeIcon(aBitmap)
.setStyle(new Notification.BigPictureStyle()
.bigPicture(aBigBitmap))
.build();
BigTextStyle
長いテキストを表示する
https://developer.android.com/reference/androidx/core/app/NotificationCompat.BigTextStyle
code:java
Notification notification = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.setStyle(new Notification.BigTextStyle()
.bigText(aVeryLongString))
.build();
InboxStyle
最大5件の通知が表示される
code:java
Notification notification = new Notification.Builder()
.setContentTitle("5 New mails from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.setStyle(new Notification.InboxStyle()
.addLine(str1)
.addLine(str2)
.setContentTitle("")
.setSummaryText("+3 more"))
.build();
MediaStyle
MessagingStyle
Go.iconこんなにスタイルがあるのは知らなかった
気になるポイント
コメント