A Jetpack Compose library to fully convert Android's Spanned into AnnotatedString.
You can use this library to display Html.fromHtml(String) on Compose Text,
Exactly similar to what was previously displayed on Android TextView.
Compose Text Vs Android TextView
AnnotatedText supports all default android spans both CharacterStyle and ParagraphStyle spans.
CharacterStyle spans:
- URLSpan
- ImageSpan
- AbsoluteSizeSpan
- RelativeSizeSpan
- BackgroundColorSpan
- ForegroundColorSpan
- StrikethroughSpan
- UnderlineSpan
- StyleSpan
- SubscriptSpan
- SuperscriptSpan
- ScaleXSpan
- SkewXSpan
- LocaleSpan
- TextAppearanceSpan
- TypefaceSpan
ParagraphStyle spans:
- QuoteSpan
- BulletSpan
- IconMarginSpan
- DrawableMarginSpan
- LeadingMarginSpan.Standard
- AlignmentSpan (v1.0.4)
- LineBackgroundSpan (v1.0.4)
- LineHeightSpan (v1.0.4)
AnnotatedText is available in mavenCentral()
Gradle
implementation 'io.github.aghajari:AnnotatedText:1.0.3'
Maven
<dependency>
<groupId>io.github.aghajari</groupId>
<artifactId>AnnotatedText</artifactId>
<version>1.0.3</version>
<type>pom</type>
</dependency>
val spanned = buildSpannedString {
append("Hello ")
inSpans(UnderlineSpan()) {
append("World!")
}
}
AnnotatedText(
text = spanned.asAnnotatedString(),
...
)
AnnotatedText(
text = "Hello <b>World!</b>".fromHtml(),
...
)
AnnotatedText(
text = "Link to <a href='https://github.com'>GitHub</b>".fromHtml(linkColor = Color.Blue),
onURLClick = { url ->
println(url)
}
)
val content = remember {
"Welcome to my <a href='https://github.com/Aghajari'>GitHub</a>".fromHtml(
spanMappers = mapOf(
URLSpan::class to {
linkColor = Color.Red
textDecoration = TextDecoration.LineThrough
}
)
)
}
AnnotatedText(
text = content,
...
)
val content = remember {
"<blockquote>Hello <b>World!</b></blockquote>".fromHtml()
}
val layoutResult = remember {
mutableStateOf<TextLayoutResult?>(null)
}
Text(
text = content.annotatedString,
inlineContent = content.getInlineContentMap(),
onTextLayout = { layoutResult.value = it },
modifier = Modifier
.annotatedTextParagraphContents(content, layoutResult)
.annotatedTextClickable(content, layoutResult) { url ->
println(url)
}
)
Amir Hossein Aghajari
Copyright 2023 Amir Hossein Aghajari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.