Created
April 5, 2022 20:18
-
-
Save josefdolezal/f1db3c9e5783ec0cfc56290b7ffe2dfb to your computer and use it in GitHub Desktop.
RichTextView Compose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Composable | |
| fun Demo() { | |
| Column { | |
| Text("This visually looks good:") | |
| TextWithItem("Some text", EmbeddedItem(12.dp, 4.dp)) | |
| Spacer(Modifier.height(20.dp)) | |
| Text("This is not aligned correctly:") | |
| TextWithItem("Some text", EmbeddedItem(12.dp, 20.dp)) | |
| } | |
| } | |
| @Composable | |
| fun TextWithItem(text: String, item: EmbeddedItem) { | |
| val density = LocalDensity.current | |
| val inlineContent = remember(item) { | |
| mapOf( | |
| "item" to InlineTextContent( | |
| placeholder = Placeholder( | |
| width = with(density) { item.width.toSp() }, | |
| height = with(density) { item.height.toSp() }, | |
| placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline | |
| ), | |
| children = { | |
| Embedded(Modifier.offset(y = item.heightBelowBaseline), item) | |
| } | |
| ) | |
| ) | |
| } | |
| Text( | |
| modifier = Modifier.background(Color.Blue), | |
| style = typography.body1, | |
| text = buildAnnotatedString { | |
| append(text) | |
| appendInlineContent("item") | |
| }, | |
| inlineContent = inlineContent | |
| ) | |
| } | |
| @Composable | |
| fun Embedded(modifier: Modifier = Modifier, item: EmbeddedItem) { | |
| Column(modifier) { | |
| Box(modifier = Modifier | |
| .size(item.width, item.heightAboveBaseline).background(Color.Red)) | |
| Box(modifier = Modifier | |
| .size(item.width, item.heightBelowBaseline).background(Color.Green)) | |
| } | |
| } | |
| data class EmbeddedItem(val heightAboveBaseline: Dp, val heightBelowBaseline: Dp, val width: Dp = 20.dp) { | |
| val height: Dp | |
| get() = heightBelowBaseline + heightAboveBaseline | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment