Jetpack Compose中的基本组件-文本组件(Text)

前言

除了布局组件外,Jetpack Compose 还提供了一系列其他常用的 UI 组件。

https://developer.android.google.cn/jetpack/compose/components?hl=zh-cn

https://developer.android.google.cn/courses/pathways/compose?hl=zh-cn

文本

Text(文本):

1
Text("Hello, World!")

文本居中

1
2
3
4
5
6
7
8
Text(
text = "A",
modifier = Modifier
.background(Color.Red)
.width(30.dp).height(30.dp)
.wrapContentSize(Alignment.Center),
textAlign = TextAlign.Center,
)

设置行数

1
2
3
4
5
6
7
8
9
Text(
text = "ABC",
modifier = Modifier
.background(Color.Red)
.width(30.dp).height(30.dp)
.wrapContentSize(Alignment.Center),
textAlign = TextAlign.Center,
maxLines = 1
)

超出省略号

1
2
3
4
5
6
7
Text(
text = "第九章 平面直角坐标平面直角坐标平面直角坐标",
fontSize = 12.sp,
color = Color.White,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)

字体粗细

1
2
3
4
Text(
text = "这是加粗的文本",
fontWeight = FontWeight.Bold
)

颜色字体封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import androidx.compose.ui.graphics.Color

object ZColorUtils {
fun hexToColor(hex: String): Color {
val tempStr = hex.removePrefix("#")
if (tempStr.length == 6) {
val r: Int = tempStr.substring(0, 2).toLong(16).toInt()
val g: Int = tempStr.substring(2, 4).toLong(16).toInt()
val b: Int = tempStr.substring(4, 6).toLong(16).toInt()
return Color(r, g, b, 255)
} else if (tempStr.length == 8) {
val r: Int = tempStr.substring(0, 2).toLong(16).toInt()
val g: Int = tempStr.substring(2, 4).toLong(16).toInt()
val b: Int = tempStr.substring(4, 6).toLong(16).toInt()
val a = tempStr.substring(6, 8).toLong(16).toInt()
return Color(r, g, b, a)
}
return Color.White
}
}

组件封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.sp
import com.xhkjedu.zxs_android.utils.ColorUtils


@Composable
fun TextColorSize(
text: String = "",
color: String = "#ffffff",
size: Int = 12
) {
val colorHex = ZColorUtils.hexToColor(color)
Text(text = text, fontSize = size.sp, color = colorHex)
}

使用

1
2
3
4
5
TextColorSizeComp(
text = "你好",
size = 10,
color = "#ffffff"
)

文字不居中

因为字体的原因导致的不居中只能使用偏移实现了

1
2
3
4
5
6
7
8
9
Text(
text = "去练习",
fontSize = 11.sp,
color = Color(0xff4B45FF),
textAlign = TextAlign.Center,
modifier = Modifier
.align(Alignment.Center)
.offset(y = (-2).dp)
)

组件提取

因为Compose组件本质都是方法,所以可以使用提取方法来提取组件

快捷键:Ctrl+Alt+M