Johann
Johann

Reputation: 29867

Show a new line in a Text component in Jetpack Compose

I want to display some text using the Text composable in Jetpack Compose and the text contains a new line character '\n'. Something like below:

Text("This is the first line\nThis is the second line")

But the '\n' ends up just being text.

How can I get the Text component to display the new line on a separate line?

Upvotes: 6

Views: 13206

Answers (3)

AndrewStone
AndrewStone

Reputation: 587

\n should work, at least on the platforms I tested.

You said "something like" -- if you are actually passing a string literal then \n will be replaced with a newline at compile time. But if you are loading the string from a file, etc, its possible that the \n was not replaced. Try:

val s = origString.replace("\\n","\n")
Text(s)

This will force the replacement of \n at runtime.

Upvotes: 0

djacobsen13
djacobsen13

Reputation: 259

Try using Text("This is the first line\r\nThis is the second line"). This should solve your problem.

Upvotes: 8

Berkay Kireçci
Berkay Kireçci

Reputation: 737

I just tried and i can see new line on preview and real device. Not sure if its about compose version or just bug. Screenshot

Upvotes: 3

Related Questions