Issue
I am working on one example using Android Jetpack Compose, where I am displaying some text equations like below :
<html>
<body>
<!-- Superscript-->
<p> E = mc<sup>2</sup></p>
<!--Subscript-->
<p> CH<sub>4</sub> + H<sub>2</sub>O = CO + 3H<sub>2</sub></p>
</body>
</html>
Does there any decoration or style mechanism exist for Text that I can use to achieve the same output?
Solution
UPDATE: Please refer new answer mentioned here: https://stackoverflow.com/a/66801935/2949612
Using BaselineShift, we can use Span for Text widget, which allows to decorate text as subscript or superscript.
Below is the working code to achieve the above output:
@Composable
fun Equations(name: String) {
val defaultStyle = TextStyle(fontSize = 20.sp,
color = Color.White)
val scriptStyleSuper = TextStyle(
baselineShift = BaselineShift.Superscript,
fontSize = 12.sp,
color = Color.Green)
val scriptStyleSub = TextStyle(
baselineShift = BaselineShift.Subscript,
fontSize = 12.sp,
color = Color.Green)
Text {
Span(text = "E = mc", style = defaultStyle) {
Span(
text = "2",
style =scriptStyleSuper
) {
Span(text = "\n")
Span(text = "CH", style = defaultStyle)
Span(text = "4 ",style = scriptStyleSub)
Span(text = "+ H", style = defaultStyle)
Span(text = "2",style = scriptStyleSub)
Span(text = "O = CO + 3H", style = defaultStyle)
Span(text = "2",style = scriptStyleSub)
}
}
}
}
Output:
To check more info: https://developer.android.com/reference/kotlin/androidx/compose/ui/text/style/package-summary
Answered By - pRaNaY
Answer Checked By - Katrina (JavaFixing Volunteer)