阅读 368

初识 Jetpack Compose(五) :组件-Text

compose-landing-roadmap.svg

目录

一、Text

Compose中的Text的作用与 xml 中的TextView无二,作用于最基本的文本显示。

1.属性

@Composable
fun Text(
    // text: String,
    text: AnnotatedString,
    modifier: Modifier = Modifier,
    color: Color = Color.Unspecified,
    fontSize: TextUnit = TextUnit.Unspecified,
    fontStyle: FontStyle? = null,
    fontWeight: FontWeight? = null,
    fontFamily: FontFamily? = null,
    letterSpacing: TextUnit = TextUnit.Unspecified,
    textDecoration: TextDecoration? = null,
    textAlign: TextAlign? = null,
    lineHeight: TextUnit = TextUnit.Unspecified,
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
    inlineContent: Map<String, InlineTextContent> = mapOf(),
    onTextLayout: (TextLayoutResult) -> Unit = {},
    style: TextStyle = LocalTextStyle.current
) {
    ...
}
复制代码
属性名类型作用
textString要显示的文本
textAnnotatedString要显示的文本,可设置文本中指定字符的颜色、字体、大小等属性
modifierModifier修饰符
fontSizeTextUnit文本字体大小
fontStyleFontStyle?文本字体变体
fontWeightfontWeight?文本字体字重
fontFamilyFontFamily?文本字体
letterSpacingTextUnit文本字符之间的间距
textDecorationTextDecoration?用于为文本绘制装饰(例如:下划线、删除线)
textAlignTextAlign?文本段落的对齐方式
lineHeightTextUnit文本段落之间的行高
overflowTextOverflow文本字符溢出的显示方式 ,同xml ellipsize
softWrapBoolean文本是否应在换行符处中断。如果为false,则文本的宽度会在水平方向上无限延伸,且textAlign属性失效,可能会出现异常情况
maxLinesInt文本可跨越的可选最大行数,必要时可以换行。如果文本超过给定的行数,则会根据textAlignsoftWrap属性截断文本。它的值必须大于零。
onTextLayout(TextLayoutResult) -> Unit计算新的文本布局时执行的回调
styleTextStyle文本的样式配置,例如颜色,字体,行高等。可参考主题-排版 使用

2.使用示例

2.1 示例一

@Composable
fun TextExampleMoney(value:Float){
    var str = value.toString()
    if(!str.contains("."))
        str+=".00"
    var strSplit = str.split(".")

    val annotatedStringBuilder = AnnotatedString.Builder()
    annotatedStringBuilder.apply {
        pushStyle(
            SpanStyle(
                color = Color.Gray,
                fontSize = 16.sp,
            )
        )
        append("¥")
        pop()
        pushStyle(
            SpanStyle(
                color = Color.DarkGray,
                fontSize = 26.sp,
                fontWeight = FontWeight.Bold
            )
        )
        append(strSplit[0])
        pop()
        pushStyle(
            SpanStyle(
                color = Color.Gray,
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold
            )
        )
        append(".${strSplit[1]}")
        pop()
    }

    Text(
        text = annotatedStringBuilder.toAnnotatedString(),
    )

}

//调用
TextExampleMoney(98.99f)
复制代码

1630916637(1).jpg

2.2 示例二

@Composable
fun TextExample(){
    val annotatedStringBuilder = AnnotatedString.Builder()
    annotatedStringBuilder.apply {
        append("Jetpack Compose ")
        pushStyle(
            SpanStyle(
                color = Color.Blue,
                fontSize = 16.sp,
            )
        )
        append("widget")
        pop()
        append(" [ ")
        pushStyle(
            SpanStyle(
                color = Color.Red,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        )
        append("Text")
        pop()
        append(" ] usage example")
    }

    Text(
        text = annotatedStringBuilder.toAnnotatedString(),
        fontSize = 16.sp,
        overflow = TextOverflow.Ellipsis,
        textAlign = TextAlign.Center
    )

}

//调用
TextExample()
复制代码

1630916734(1).jpg

2.3 示例三

Text(
    text = "High level element that displays text and provides semantics / accessibility information.\n" +
            "\n" +
            "The default style uses the LocalTextStyle provided by the MaterialTheme / components. If you are setting your own style, you may want to consider first retrieving LocalTextStyle, and using TextStyle.copy to keep any theme defined attributes, only modifying the specific attributes you want to override.\n" +
            "\n" +
            "For ease of use, commonly used parameters from TextStyle are also present here. The order of precedence is as follows:\n" +
            "\n" +
            "If a parameter is explicitly set here (i.e, it is notnull or TextUnit.Unspecified), then this parameter will always be used.\n" +
            "\n" +
            "If a parameter is not set, (null or TextUnit.Unspecified), then the corresponding value from style will be used instead.\n" +
            "\n" +
            "Additionally, for color, if color is not set, and style does not have a color, then LocalContentColor will be used with an alpha of LocalContentAlpha- this allows this Text or element containing this Text to adapt to different background colors and still maintain contrast and accessibility.",
    fontSize = 16.sp,
    overflow = TextOverflow.Ellipsis,
    textAlign = TextAlign.Start,
    style = MaterialTheme.typography.Description,
    maxLines = 20,
    lineHeight = 20.sp,
    textDecoration = TextDecoration.Underline
)
复制代码

image.png

二、ClickableText

在一些开发需求中,我们需要监听一个Text的某一段区域的Touch事件,比如:
请阅读并同意《xxx用户使用协议》,我们需要监听书名号内的文字的点击事件并进行跳转,ClickableText可以很轻松的帮我们做到这一点。

@Composable
fun ClickableText(
    text: AnnotatedString,
    modifier: Modifier = Modifier,
    style: TextStyle = TextStyle.Default,
    softWrap: Boolean = true,
    overflow: TextOverflow = TextOverflow.Clip,
    maxLines: Int = Int.MAX_VALUE,
    onTextLayout: (TextLayoutResult) -> Unit = {},
    //点击事件监听,参数为触发事件时点击的字符在文本中的位置
    onClick: (Int) -> Unit
) {
...
}
复制代码

通过源码得知,ClickableText区别于Text外,额外提供了onClick回调,会返回我们点击文本时,手指所点击的字符在文本中的位置。 比如:

ClickableText(
    text = annotatedStringBuilder.toAnnotatedString(),
    overflow = TextOverflow.Ellipsis
){
    Log.d("ClickableText", "$it -> character is clicked.")
}
复制代码

image.png

预计在未来还会提供LongClickableText:文本的长按事件,不过目前暂未支持。

三、最后

好记性不如烂笔头,初识 Jetpack Compose 系列是我自己的学习笔记,在加深知识巩固的同时,也可以锻炼一下写作技能。文章中的内容仅作参考,如有问题请留言指正。

1. 参考

文章分类
Android