Text 通常是我們接觸 Compose 看到的第一個元件,Text 元件挺簡單的,但是也有一些值得學習的技巧。
程式碼範例
基本用法
@Composable
fun TextDem(name: String) {
Text(
text = "Hello $name!",
color = Color.Blue,
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic,
maxLines = 2,
textAlign = TextAlign.Center,
modifier = Modifier
.width(200.dp),
)
}
使用 TextStyle 達到同樣的效果
我們可以將多種的樣式參數集合起來,用 TextStyle 來指定其 styel
@Composable
fun TextDemo(name: String) {
Text(
text = "Hello $name!",
style = TextStyle(
color = Color.Blue,
fontSize = 32.sp,
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic,
),
maxLines = 1,
textAlign = TextAlign.Center,
modifier = Modifier
.width(200.dp),
)
}
也可以將自訂的 TextStyle 存成變數,重覆利用
@Composable
fun TextDemo(name: String) {
val myStyle = TextStyle(
color = Color.Blue,
fontSize = 32.sp,
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic,
shadow = Shadow(
color = Color.Red,
offset = Offset(5.0f, 10.0f),
blurRadius = 3f,
)
)
Text(
text = "Hello $name!",
style = myStyle,
)
}
使用 Material Theme 內建的 Style
@Composable
fun TextDemo(name: String) {
Text(
text = "Hello, $name",
style = MaterialTheme.typography.titleLarge,
)
}
常用於配合的 Modifier
@Composable
fun TextDemo() {
Text(
text = "Hello World!",
modifier = Modifier
.background(Color.Green)
.width(180.dp)
.height(50.dp)
.padding(16.dp)
.clickable(onClick = { }),
style = MaterialTheme.typography.titleLarge
)
}
函式庫版本
// 早期版本 import androidx.compose.fundation.Text import androidx.compose.material.Text // 較新版本 import androidx.compose.material3.Text
Comments