Android Compose UI Text 文字樣式與 Typography

Text 是最基本的 Composable,但它功能非常強大。

基礎樣式設定

Text 提供了許多參數來設定樣式:

Text(
    text = "Hello World",
    color = Color.Blue,
    fontSize = 24.sp,
    fontWeight = FontWeight.Bold,
    fontStyle = FontStyle.Italic,
    textAlign = TextAlign.Center,
    overflow = TextOverflow.Ellipsis, // 文字過長時顯示 ...
    maxLines = 1,
    style = MaterialTheme.typography.bodyLarge // 使用主題樣式
)

AnnotatedString (多樣式文字)

如果你想要在同一行文字中混合不同的樣式(例如:部分粗體、部分紅色),你需要使用 AnnotatedString

我們使用 buildAnnotatedString 來建構:

val styledText = buildAnnotatedString {
    append("這是一段 ")
    
    withStyle(style = SpanStyle(color = Color.Red, fontWeight = FontWeight.Bold)) {
        append("重要的文字")
    }
    
    append(",然後回復正常。")
}

Text(text = styledText)

這比傳統 TextView 使用 SpannableString 簡單直觀得多。

自定義字型 (Custom Fonts)

要在 Compose 中使用自定義字型 (如 .ttf, .otf):

  1. res/ 資料夾下建立 font 資料夾。
  2. 將字型檔放入 (例如 my_font.ttf)。
  3. 建立 FontFamily 物件。
val MyFontFamily = FontFamily(
    Font(R.font.my_font_regular, FontWeight.Normal),
    Font(R.font.my_font_bold, FontWeight.Bold)
)

Text(
    text = "Custom Font Text",
    fontFamily = MyFontFamily
)

Google Fonts (Downloadable Fonts)

從 Compose 1.2 開始,支援可下載字型,這能大幅減少 APK 體積。

你需要使用 GoogleFont 依賴: implementation("androidx.compose.ui:ui-text-google-fonts:1.x.x")

val provider = GoogleFont.Provider(...)
val fontName = GoogleFont("Lobster")
val fontFamily = FontFamily(
    Font(googleFont = fontName, fontProvider = provider)
)

Typography 主題系統

為了保持 App 設計的一致性(這點非常重要!),你不應該到處寫死 fontSize = 20.sp。最好是定義一套 Typography 主題,並在全域使用。

ui/theme/Type.kt 中定義:

val Typography = Typography(
    bodyLarge = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.Normal,
        fontSize = 16.sp,
        lineHeight = 24.sp,
        letterSpacing = 0.5.sp
    )
    // 定義其他如 titleLarge, labelSmall 等
)

使用時:

Text(
    text = "內文",
    style = MaterialTheme.typography.bodyLarge
)

這樣當設計師要修改全站內文字體大小時,你只需要改一個地方。

小結

Text 不只是顯示文字,配合 AnnotatedString 與完整的 Typography 系統,能打造出閱讀體驗極佳的介面。