Jetpack Compose Text Hyphenation

1.8k Views Asked by At

How do I get words to break correctly to new lines in Android with Jetpack Compose? I know the functionality from the web, where I use ­ for such cases.

I defined string values with possible line breaks like this: Korrespondenz\u00ADsprache. Unfortunately this does not work for Android.

I use the following code

Text(
    text = "Korrespondenz\u00ADsprache",
    style = MaterialTheme.typography.h4
)

Currently the result looks like this:

enter image description here

The expected result should look like this:

enter image description here

3

There are 3 best solutions below

2
Gabriele Mariotti On BEST ANSWER

You can override the default configuration of the hyphenation configuration (Hyphens = Hyphens.None) using:

   Text(
       text = "Korrespondenz\u00ADsprache",
       style = MaterialTheme.typography.h4.copy(hyphens = Hyphens.Auto)
   )

enter image description here

With Auto the words will be automatically broken at appropriate hyphenation points.

It requires 1.3.0-rc01

0
z.g.y On

Looks like hyphen is just recently supported in Compose 1.3.0-rc01 release candidate as part of Experimental API

https://developer.android.com/jetpack/androidx/releases/compose-ui#1.3.0-rc01

And you might expect something like this in TextStyle parameters in that compose version

(
...
 hyphens = Hyphens.Auto
...
)
0
VictorPurMar On

Yes, compose now includes a hyphens strategy inside TextStyle adding Hyphens.Autoas the other responses explain.

Still, I was not getting the result I was looking for after adding this parameter. In most of the cases, the break '-' was not being applied since Android, by default, tried not to break the word if possible.

To allow the hyphens to be applied for example to a paragraph you also should add one more TextStyle property, lineBreak then it will be something like

 Text(
        text = "Korrespondenz\u00ADsprache",
        style = MaterialTheme.typography.h4.copy(
                hyphens = Hyphens.Auto,
                lineBreak = LineBreak.Paragraph)
 )