Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android embed newline in a notification

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?

like image 396
miannelle2 Avatar asked Feb 22 '12 01:02

miannelle2


People also ask

How do I add a line break in Android?

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.

How do you extend notifications?

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.


1 Answers

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:

  1. The title can have no formatting (i.e. don't try to use HTML here)
  2. The body can have as much formatting as we want, but we must note that the line breaks won’t display when the notification is collapsed. All other HTML formatting works fine in both collapsed/expanded states. You can bold, italicize, etc. as much as you want (I think)

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

like image 199
w3bshark Avatar answered Oct 12 '22 22:10

w3bshark