This section describes apis related to the Text control

Text in Compose is equivalent to TextView in Android native, and the API is simpler:

Fun Text(Text: String, // Text content, can directly pass String, can also use stringResource(id = R.stabilizer. Hello) to specify the modifier: Modifier = Modifier, // Modifier, can specify width and height, background, click events, etc. Unspecified, // The text color of fontSize: TextUnit = TextUnit.Unspecified, // The text size of fontStyle: fontStyle? = null, // font style, such as italics fontWeight: fontWeight? = null, // font width, such as bold fontFamily: fontFamily? LetterSpacing: TextUnit = TextUnit.Unspecified, // textDecoration: TextDecoration? = null, // ornament, such as underline textAlign: textAlign? TextUnit = TextUnit.Unspecified, // lineHeight overflow: TextUnit = TextUnit.Unspecified, // lineHeight overflow: TextOverflow = TexToverflow.clip, // Display the overflow of text, such as clipping, or display at the end... Boolean = true, // maxLines: Int = Int.MAX_VALUE, // maximum number of lines onTextLayout: (TextLayoutResult) -> Unit = {}, // Layout change callback style: TextStyle = localTextstyle. current // set style, similar to TextView style)Copy the code

TextStyle API, content and Text inside most of the same, specific can View the related API, here there is a point to mention: Text can not be vertical center, to vertical center, can be outside a layer of parent View, such as Box.

Based on the sample

Let’s do a little Demo

@Composable fun TextDemo() { val text = "this is compose text demo, Which likes TextView in Android Native XML layout" Text(Text = Text, // Text color = color.green, // font color fontSize = 16.sp, // fontSize fontStyle = fontstyle.italic, // fontWeight = fontweight.bold, // Bold textAlign = textalign.center, // Align: // Specify width = 300dp maxLines = 2, // maxLines = 2 overflow = textoverflow.ellipsis, / / text overflow after cutting softWrap = true, / / text is too long if wrap textDecoration = textDecoration. Underline, / / text decoration, here to add an underscore)}Copy the code

The effect is as follows:

Then we add the font style:

FontFamily = fontFamily.Cursive, // Font styleCopy the code

The effect is as follows:

Let’s add line height and character spacing:

LineHeight = 40.sp, lineHeight = 40sp letterSpacing = 5.spCopy the code

The effect is as follows:

The rich text

For example, if you want to use a native TextView and you want to implement rich text, you have to use Spanable, and you have to subscript the text, which is pretty cumbersome, for example, Compose.

Use SpanStyle to implement rich text

The API is as follows:

Class SpanStyle(val color: color = color.Unspecified, // val fontSize: TextUnit = Textunit. Unspecified, // The text size val fontWeight: fontWeight? = null, // var fontStyle: fontStyle? = null, // text style, such as italics val fontSynthesis: fontSynthesis? Val fontFamily: fontFamily? Val fontFamily: fontFamily? Serif val fontFeatureSettings: String? = null, // set the font to the same value as the CSS feature Settings val letterSpacing: TextUnit = TextUnit.Unspecified, // Character spacing val baselineShift: baselineShift? Val textGeometricTransform: textGeometricTransform? Val textGeometricTransform: textGeometricTransform? Val localeList: localeList? Val localeList: localeList? Val background: Color = color. Unspecified, // Background Color val textDecoration: textDecoration? Val shadow: shadow? = null // Shadow)Copy the code

See the Demo directly:

@composable Fun TextDemo2() {Text(buildAnnotatedString) {// Use white background, red font, 18SP, Monospace font to draw "Hello "withStyle(style = SpanStyle(color = color.red, background = color.white, Monospace) {append("Hello ")} // Draw "World" ("World ") Green, 18SP, Serif, Color = color.Green, background = color.Yellow, fontSize = 30.sp, fontFamily = FontFamily.Serif, W900) {append("Click")} append(" Me") // add shading and geometry withStyle(style = SpanStyle(color = color.Yellow, background = color.White, baselineShift = baselineShift (1.f), // Offset 10 textGeometricTransform = textGeometricTransform (scaleX = 2.0f, skewX = 0.5f), Color = color. Blue, offset = offset (x = 1.0f, y = 1.0f), // blurRadius = 10.0f)) {append(" Effect")}})}Copy the code

BuildAnnotatedString () builds a scope in which you can use withStyle(style) to specify the literal format.

2 Use ParagraphStyle to implement paragraphs

The API is as follows:

class ParagraphStyle constructor( val textAlign: TextAlign? Val textDirection: textDirection? Val lineHeight: TextUnit = TextUnit.Unspecified, // lineHeight val textIndent: textIndent? = null // indent mode)Copy the code

See the Demo directly:

@Composable
fun TextDemo3() {
    Text(buildAnnotatedString {
        // 指定对齐方式为Start,通过textIndent指定第一行每段第一行缩进32sp,其余行缩进8sp
        withStyle(style = ParagraphStyle(textAlign = TextAlign.Start, textIndent = TextIndent(firstLine = 32.sp, restLine = 8.sp))) {

            // 第一段,因为只有一行,所以直接缩进32sp
            withStyle(style = SpanStyle(color = Color.Red)) {
                append("Hello, this is first paragraph\n")
            }
            // 第二段(第一行会缩进32sp,后续每行会缩进8sp)
            withStyle(style = SpanStyle(color = Color.Green, fontWeight = FontWeight.Bold)) {
                append("Hello, this is second paragraph,very long very long very long very long very long very long very long very long very long very long\n")
            }
            // 第三段,因为只有一行,所以直接缩进32sp
            append("Hello, this is third paragraph\n")
        }
    })
}
Copy the code

The effect is as follows:

interaction

Traditional Android TextView can be selected/unselected, but it is difficult to achieve part of the selected, part of the unselected; For example, a traditional TextView can set the click event, but it’s hard to get the location of the click text in Compose, which isn’t a problem in Compose.

1 Select and unselect

We can directly use SelectionContainer to include the selected text and DisableSelection to include the unselected text, eg:

@Composable Fun TextDemo4() {// Set optional area SelectionContainer {// Column is equivalent to vertical LinearLayout Column {Text(Text = "You can select me, DisableSelection {Text(Text = "DisableSelection ")} // DisableSelection {Text(Text =" DisableSelection ")} You can select me ")Copy the code

The effect is as follows:

2 A single text responds to the click event

We can use ClickableText directly to achieve the effect of clicking on a text. The API is as follows:

Fun ClickableText(text: AnnotatedString, // AnnotatedString); TextStyle = TextStyle.Default, // text-style softWrap: Boolean = true, // text-style overflow: MaxLines: Int = Int.MAX_VALUE, // Maximum number of lines (TextLayoutResult) -> Unit = {}, // layout change callback onClick: (Int) -> UnitCopy the code

The Demo is as follows:

@Composable fun TextDemo5(context: MakeText (Context) {ClickableText(text = AnnotatedString(" please click on me "), onClick = {index -> toast.maketext (Context, "click on location :$index", Toast.LENGTH_SHORT).show() }) }Copy the code

The effect is as follows:

If you want to set the whole Text() click event, use the Modifier. Clickable {} directly.

3 annotate the specified text (hyperlink)

We can use pushStringAnnotation() and pop() to annotate a given text, as follows:

@composable Fun TextDemo6(Context: context) {val url_tag = "article_URL "; Val articleText = buildAnnotatedString {appEnd (" click ") // pushStringAnnotation() You can think of it as constructing a <tag annotation> map pushStringAnnotation(tag = url_tag, The annotation = "https://devloper.android.com") / / to add annotation text to "show the Android's official website" withStyle (style SpanStyle = (color = color Blue, FontWeight = fontweight.bold)) {append(" display Android website ")} // pop() means the end of the annotation pop()} // Build ClickableText(text = ArticleText, onClick = {index - > / / according to remove the tag annotation and print articleText getStringAnnotations (tag = url_tag, Start = index, end = index).firstornull ()?.let {annotation -> toast.maketext (context, "click :${annotation. Item}", Toast.LENGTH_SHORT).show() } }) }Copy the code

The effect is as follows:

Demo can be downloaded here: gitee.com/lloydfinch/…

Of course, there’s more to Text than that, and you can check out the official API for more.