@Composable
fun Text(
    text: String,
    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,
    onTextLayout: (TextLayoutResult) -> Unit = {},
    style: TextStyle = LocalTextStyle.current
)

 

 

 

 

字体大小、颜色、粗细、斜体样式

@Composable
fun TextTestView() {
    val content =
        "Hello Compose!"
    Column(Modifier.fillMaxSize()) {
        Text(
            text = content,
            fontSize = 20.sp, // 字体大小
            color = colorResource(id = R.color.purple_200), // 字体颜色
            fontWeight = FontWeight.Bold, // 字体加粗
            fontStyle = FontStyle.Italic // 字体斜体
        )
    }
}

单行 / 多行,超出显示 ...

在属性介绍中讲解了设置单行不允许换行 softWrap、设置最多显示几行 maxLines、内容超出截取显示 overflow,下面使用代码演示。

设置单行不允许换行,文字超出显示 ... 

@Composable
fun TextTestView() {
    val content =
        "文字对任何界面都属于核心内容,而利用 Jetpack Compose 可以更轻松地显示或写入文字。Compose 可以充分利用其构建块的组合,这意味着您无需覆盖各种属性和方法,也无需扩展大型类,即可拥有特定的可组合项设计以及按您期望的方式运行的逻辑。"
        
    Column(Modifier.fillMaxSize()) {
        Text(text = content, softWrap = false, overflow = TextOverflow.Ellipsis)
    }
}

设置多行,超出显示 ...

@Composable
fun TextTestView() {
    val content =
        "文字对任何界面都属于核心内容,而利用 Jetpack Compose 可以更轻松地显示或写入文字。Compose 可以充分利用其构建块的组合,这意味着您无需覆盖各种属性和方法,也无需扩展大型类,即可拥有特定的可组合项设计以及按您期望的方式运行的逻辑。"
        
    Column(Modifier.fillMaxSize()) {
        Text(text = content, maxLines = 3, overflow = TextOverflow.Ellipsis)
    }
}

字体 / 引用字体文件

Compose 内置了几种字体格式,使用 FontFamily. 设置。

@Composable
fun TextTestView() {
    val content = "Hello Compose!"
    Column(Modifier.fillMaxSize()) {
        Text(
            text = content,
            fontSize = 30.sp,
            fontFamily = FontFamily.Cursive
        )
    }
}

 Compose 只提供了四种字体格式是远远不够的,开发者可以引用其他的字体格式文件。 在 res 文件夹下创建 font 文件夹,将 .ttf 的字体格式文件放入该文件夹下,通过代码设置给 Text

@Composable
fun TextTestView() {
    val content = "Hello Compose!"
    Column(Modifier.fillMaxSize()) {
        Text(
            text = content,
            fontSize = 30.sp,
            fontFamily = FontFamily(Font(R.font.panda_font))
        )
    }
}

字间距 / 行间距

设置间距和行距使用的是 sp,因为可能机型系统不同,设置老年人模式或设置统一的字体大小,使用 sp 会根据设置改变。dp 是不会的,Compose 也是强制使用 sp 。

@Composable
fun TextTestView() {
    val content = "Hello Compose!\nHello Compose!"
    Column(Modifier.fillMaxSize()) {
        Text(
            text = content,
            lineHeight = 30.sp,
            letterSpacing = 20.sp
        )
    }
}

中划线 / 下划线

@Composable
fun TextTestView() {
    val content = "Hello Compose!"
    Column(Modifier.fillMaxSize()) {
        Text(
            text = content,
            textDecoration = TextDecoration.Underline
        )
 
        Text(
            text = content,
            textDecoration = TextDecoration.LineThrough
        )
    }
}

文字对齐方向,下面以水平居中为列子:

@Composable
fun TextTestView() {
    val content = "Hello Compose!\nHello Compose!"
    Column(Modifier.fillMaxSize()) {
        Text(
            text = content,
            modifier = Modifier
                .size(300.dp, 50.dp)
                .background(Color.Gray),
            textAlign = TextAlign.Center
        )
 
    }
}

选择文本内容、复制等操作

Text 默认是不支持选择复制的,需要给它包一层 SelectionContainer{}函数,可以在任意层,比如 Text 父 View 的父 View ... 只要包着 Text 就有效。

@Composable
fun TextTestView() {
    SelectionContainer {
        Text("Hello Compose!")
    }
}

字体缩放比例,倾斜角度

Text 设置水平方向缩放比例,倾斜角度使用 textGeometricTransform 设置,其中有两个参数 scaleX 设置文字内容水平方向缩放比例,skewX 设置文字水平方向剪裁倾斜角度。

@Composable
fun TextTestView() {
    val content = "Hello Compose!"
    Column(Modifier.fillMaxSize()) {
        Text(
            text = content,
            style = TextStyle(textGeometricTransform = TextGeometricTransform(2f, -0.5f))
        )
    }
}

文本内容段落缩进

Text 设置段落缩进使用 textIndent,两个参数 firstLine 和 restLine 分别是设置第一行缩进量和其余行的缩进量。

@Composable
fun TextTestView() {
    val content = "文字对任何界面都属于核心内容,而利用 Jetpack Compose 可以更轻松地显示或写入文字。Compose 可以充分利用其构建块的组合,这意味着您无需覆盖各种属性和方法,也无需扩展大型类,即可拥有特定的可组合项设计以及按您期望的方式运行的逻辑。"\n"
    Column(Modifier.fillMaxSize()) {
        Text(
            text = content,
            style = TextStyle(textIndent = TextIndent(20.sp, 10.sp))
        )
    }
}

文本内容多段不同样式
开发中经常会有这种需求,一串字符串中一部分显示不同颜色或加粗等样式的需求,Compose 提供了 buildAnnotatedString{} 文字构建器、withStyle() 设置该段文本的样式(在属性介绍中讲解了具体参数)、append() 文本链接。

下面以常见的隐私协议样式来展示,看代码更好理解。


在代码中可看出每个文本都在 withStyle 中,分别可以设置不同样式,灵活性高不仅可以设置样式,多段点击也是这样实现,下面 交互详解 中介绍。
 

点击监听

Text 点击监听使用 Modifier 设置

@Composable
fun TextTestView() {
   val content =
       "Hello Compose!"
 
   var clickNum by remember {
       mutableStateOf(0)
   }
 
   Text(
       text = content + clickNum,
       modifier = Modifier.clickable(
           onClick = {
               clickNum += 1
           })
   )
}

代码中使用了 Compose 的 remember 和 mutableStateOf 函数,mutableStateOf 是做数据绑定和变动通知的类似 Jetpack 的 liveData,后面写一篇文章详细介绍。

上面代码创建 int 类型变量 clickNum,填写 Text 中显示 UI,点击 Text clickNum + 1,Text 收到变量更新后自动刷新显示新的值,下面看实现效果。

文本多段点击监听
不同位置点击监听使用 ClickableText,它也是继承于 BasicText,只是比 Text 多了 onClick 参数,返回点击内容位置的下标。
 

@Composable
fun TextTestView() {
 
    var clickIndex by remember {
        mutableStateOf(0)
    }
 
    ClickableText(
        text = buildAnnotatedString {
            append("您好,请同意《掘金隐私协议》才可以登陆。")
        },
 
        ) { contentIndex ->
        clickIndex = contentIndex
    }
 
    Text(
        text = "点击的文字下标:${clickIndex}",
        modifier = Modifier.padding(top = 20.dp)
    )
}

这样就可以根据文字下标来判断点击范围。
下面使用 List 将需要点击的文字下标存下,点击时判断范围。

@Composable
fun TextTestView() {
 
    var clickIndex by remember {
        mutableStateOf("")
    }
 
    val clickIndexList: MutableList<Pair<Int, Int>> = ArrayList()
 
    ClickableText(
        text = buildAnnotatedString {
            append("您好,请同意")
 
            withStyle(
                style = SpanStyle(
                    fontWeight = FontWeight.Bold,
                    textDecoration = TextDecoration.Underline
                )
            ) {
                val firstIndex = this.length + 1 // 下标开始
                append("《掘金隐私协议》")
                val endIndex = this.length // 下标结束
                clickIndexList.add(Pair(firstIndex, endIndex))
            }
            append("才可以登陆。")
        },
 
        ) { contentIndex ->
        clickIndex = when (contentIndex) {
            in clickIndexList[0].first..clickIndexList[0].second -> {
                "点击了隐私协议"
            }
            else -> {
                "点击了其他范围"
            }
        }
    }
 
    Text(
        text = clickIndex,
        modifier = Modifier.padding(top = 20.dp)
    )
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐