#Compose 中的文字
文字是所有使用者介面的核心,Jetpack Compose 可讓系統以更簡單的方式顯示或撰寫文字。Compose 可以善用其建構塊的組合,這意味著您不需要覆寫屬性和方法,也不需要擴充大型類別,即可擁有特定可組合項設計以及按照您想要的方式執行的邏輯。
範例code:
@Composable
fun Greeting(name: String) {
Column() {
//顯示文字
Text(text = "Hello $name!")
//讀取String.xml id
Text(stringResource(id= R.string.string_xml))
//設定文字顏色
Text(text = "Hello $name!"+"_Color", color = Color(0xFF0000))
//設定文字大小
Text(text = "Hello $name!"+"_Size", fontSize = 20.sp)
//設定文字為斜體
Text(text = "Hello $name!"+"_Italic", fontStyle = FontStyle.Normal)
//設定文字為粗體
Text(text = "Hello $name!"+"_Bold", fontWeight = FontWeight.Bold)
//設定文字對齊置中
Text(text = "Hello $name!"+"_Align", textAlign = TextAlign.Center,
modifier = Modifier.width(200.dp))
//設定文字陰影
val offset = Offset(5.0f, 10.0f)
Text(text = "Hello $name!"+"_Shadow", style = TextStyle(
fontSize = 16.sp,
shadow = Shadow(
color = Color.Blue,
offset = offset,
blurRadius = 3f
)
))
//設定文字字體
Text(text = "Hello $name!"+"_Serif", fontFamily = FontFamily.Serif)
//文字中的多種樣式
Text(
buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.Blue)) {
append("Hello")
}
append("$name!")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
append("W")
}
append("orld")
})
//設定行數上限
Text(text = ("Hello $name!"+"_maxlines").repeat(10), maxLines = 2)
//設定文字溢位,變顯示...
Text(text = ("Hello $name!"+"_overflow").repeat(10), maxLines = 2,overflow = TextOverflow.Ellipsis)
//設定選取文字操作
SelectionContainer {
Column() {
Text(text = "Hello $name!" + "_Selection")
DisableSelection {
Text("Hello $name!"+ "_NotSelection")
}
Text(text = "Hello $name!" + "_Selection2")
}
}
//設定點擊文字
ClickableText(
text = AnnotatedString("Hello $name!"+"Click Me"),
onClick = { offset ->
Log.d("ClickText", "第"+"$offset 個 is clicked.")
}
)
}
}
執行畫面和log
https://developer.android.com/jetpack/compose/text
https://developer.android.com/reference/kotlin/androidx/compose/ui/text/font/FontWeight