Reputation: 2382
I am setting TextStyle to my Text composable, but when the text is multi-line, only then the line height works as expected.
But, in case the text is single line, line height is not applied to it.
When I checked the documentation of TextStyle, I got to know that the lineHeight is applied on the Paragraph.
Is there a way lineHeight can be applied to single line text as well? Or is there some other attribute which I am unaware of? Please guide.
Upvotes: 5
Views: 819
Reputation: 139
This maybe late for questioner, but it would be useful for anyone else:
By default, Android will clip lineHeightPadding
, include top padding for first line, and bottom padding for last line. So when we set line height to some big values, it will become like this:
Since one-line text only have one line (obviously), text's lineHeightPadding
being trimmed both top and bottom of that line.
Since compose 1.2.0, there is new fields added to TextStyle
, that include lineHeightStyle
, provide option to trim lineHeightPadding
or not:
Text(
text = "String Text",
style = textStyle.copy(
fontSize = 14.sp,
lineHeight = 20.sp,
lineHeightStyle = LineHeightStyle(
LineHeightStyle.Alignment.Center,
trim = LineHeightStyle.Trim.None
)
)
)
Hope this help
Upvotes: 3
Reputation: 1332
lineHeight never works on single line on both xml and compose, as a workaround for both you can set minHeight as the desired lineHeight, also set text to be centered vertically.
@Composable
fun SingleLineText(
text: String,
modifier: Modifier = Modifier,
style: TextStyle = Text1Regular.copy(color = AppTheme.colors.textPrimary),
overflow: TextOverflow = TextOverflow.Ellipsis,
textAlign: TextAlign? = null
) {
Text(
modifier = modifier
.defaultMinSize(minHeight = with(LocalDensity.current) { style.lineHeight.toDp() })
.wrapContentHeight(align = Alignment.CenterVertically),
text = text,
style = style,
maxLines = 1,
overflow = overflow,
textAlign = textAlign
)
}
the key point here is these two lines
.defaultMinSize(minHeight = with(LocalDensity.current) { style.lineHeight.toDp() })
.wrapContentHeight(align = Alignment.CenterVertically),
first line to set lineHeight from your style as minHeight.
second line to center the text vertically.
BONUS for xml ->
<TextView
android:id="@+id/title_textview"
style="@style/your_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="end"
android:gravity="center_vertical" // <-------
android:maxLines="1"
android:minHeight="28sp" // <-------
tools:text="Name Surname" />
Upvotes: 2