I need to embed a newline in a notification. I have two lines of data that are different and I need to embed a newline to distinguish between the two. I trued a backslash-n, but that does not work.
Is there a way to do this?
Just add a \n to your text. This can be done directly in your layout file, or in a string resource and will cleanly break the text in your TextView to the next line.
To expand a notification, tap the Down arrow . Then, to act directly from a notification, tap an action, like Reply or Archive. Some apps show a dot when you get a notification. Touch and hold the app with the dot to see the oldest notification.
You do not need to use RemoteViews or a custom layout to show multiple lines, despite what others have said here! Multiline texts are possible, but only when the notification is expanded.
To do this, you can use NotificationCompat.BigTextStyle. And if you read the dev guides here then you'll notice that they mention this tip:
Tip: To add formatting in your text (bold, italic, line breaks, and so on), you can add styling with HTML markup.
So, in other words:
val title = "My Title"
val body = "Line 1<br>Line 2<br><i>Italic Line 3</i>"
val formattedBody = SpannableString(
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) Html.fromHtml(body)
else Html.fromHtml(body, Html.FROM_HTML_MODE_LEGACY)
)
NotificationCompat.Builder(context, channelId)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setContentTitle(title)
.setContentText(formattedBody)
.setStyle(NotificationCompat.BigTextStyle().bigText(formattedBody).setBigContentTitle(title))
.setSmallIcon(R.drawable.ic_small_notification_icon)
.build()
Things to note about how this works:
If you don't want to send HTML formatting in your push notification, then another option is to use markdown formatting of some sort and manually handle this before your notification building by using SpannableStringBuilder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With