Skip to content

Commit 5b9cee2

Browse files
committed
Add Resources.getAnnotatedString
1 parent b1376a5 commit 5b9cee2

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

composed/src/main/kotlin/com/w2sv/composed/Resources.kt

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,32 @@ fun rememberStyledTextResource(@StringRes id: Int, vararg formatArgs: Any): Anno
5252
val resources = LocalContext.current.resources
5353
val density = LocalDensity.current
5454
return remember(id, *formatArgs) {
55-
spannableStringToAnnotatedString(
56-
text = resources.getHtmlText(id, *formatArgs),
57-
density = density
58-
)
55+
resources.getAnnotatedString(id, density, *formatArgs)
5956
}
6057
}
6158

59+
/**
60+
* Converts a html-styled resource text to an [AnnotatedString].
61+
* #
62+
* Tested with:
63+
* - bold: <b>
64+
* - italic: <i>
65+
* - underline: <u>
66+
* - subscript: <sub>
67+
* - superscript: <sup>
68+
* - foreground color: <font color="#9900FF">
69+
* - monospace font family: <font face="monospace">
70+
*/
71+
fun Resources.getAnnotatedString(
72+
@StringRes id: Int,
73+
density: Density? = null,
74+
vararg formatArgs: Any
75+
): AnnotatedString =
76+
spannableStringToAnnotatedString(
77+
text = getHtmlText(id, *formatArgs),
78+
density = density
79+
)
80+
6281
private fun Resources.getHtmlText(@StringRes id: Int, vararg args: Any): Spanned {
6382
return HtmlCompat.fromHtml(
6483
String.format(
@@ -80,7 +99,7 @@ private fun Spanned.toHtmlWithoutParagraphs(): String {
8099

81100
private fun spannableStringToAnnotatedString(
82101
text: Spanned,
83-
density: Density
102+
density: Density?
84103
): AnnotatedString {
85104
return buildAnnotatedString {
86105
append(text)
@@ -117,8 +136,10 @@ private fun spannableStringToAnnotatedString(
117136
}
118137
)
119138

120-
is AbsoluteSizeSpan -> density.run {
121-
SpanStyle(fontSize = if (span.dip) span.size.dp.toSp() else span.size.toSp())
139+
is AbsoluteSizeSpan -> {
140+
density
141+
?.run { SpanStyle(fontSize = if (span.dip) span.size.dp.toSp() else span.size.toSp()) }
142+
?: throw IllegalArgumentException("Found AbsoluteSizeSpan but passed density null. Pass a Density to convert.")
122143
}
123144

124145
is RelativeSizeSpan -> SpanStyle(fontSize = span.sizeChange.em)

0 commit comments

Comments
 (0)