Compose 可存取 Android 專案中定義的資源。
最常見的資源類型是字串。
Text(
text = stringResource(R.string.compose)
)
stringResource 也適用於位置格式設定。
在String.xml
- Happy %1$s %2$d
Text(
text = stringResource(R.string.congratulate, "New Year", 2021)
)
可以使用 dimensionResource API,從資源 XML 檔案取得尺寸。
在res/values/dimens.xml
- 8dp
val smallPadding = dimensionResource(R.dimen.padding_small)
Text(
text = "...",
modifier = Modifier.padding(smallPadding)
)
使用 colorResource API 從資源 XML 檔案取得顏色。
在res/colors.xml
- #757575
Divider(color = colorResource(R.color.colorGrey))
使用 painterResource API 可載入向量可繪項目或光柵化素材資源格式。
在res/drawable
- res/drawable-nodpi/ic_logo.xml
- res/drawable-xxhdpi/ic_logo.png
Icon(
painter = painterResource(id = R.drawable.ic_logo),
contentDescription = null // decorative element
)
使用 AnimatedImageVector.animatedVectorResource API 可載入動畫向量可繪項目 XML。
在 res/drawable
- res/drawable/animated_vector.xml
val image = AnimatedImageVector.animatedVectorResource(R.drawable.animated_vector)
val atEnd by remember { mutableStateOf(false) }
Icon(
painter = rememberAnimatedVectorPainter(image, atEnd),
contentDescription = null // decorative element
)
Icons是在 Compose 中的質感設計圖示。
dependencies {
...
implementation "androidx.compose.material:material-icons-extended:$compose_version"
}
import androidx.compose.material.Icon
Icon(Icons.Rounded.Menu, contentDescription = "Localized description")
在 Compose 中使用字型,請將字型檔案放入 res/font 資料夾,即可直接下載這些檔案並納入 APK 中。
// Define and load the fonts of the app
private val light = Font(R.font.raleway_light, FontWeight.W300)
private val regular = Font(R.font.raleway_regular, FontWeight.W400)
private val medium = Font(R.font.raleway_medium, FontWeight.W500)
private val semibold = Font(R.font.raleway_semibold, FontWeight.W600)
// Create a font family to use in TextStyles
private val craneFontFamily = FontFamily(light, regular, medium, semibold)
// Use the font family to define a custom typography
val craneTypography = Typography(
defaultFontFamily = craneFontFamily,
/* ... */
)
// Pass the typography to a MaterialTheme that will create a theme using
// that typography in the part of the UI hierarchy where this theme is used
@Composable
fun CraneTheme(content: @Composable () -> Unit) {
MaterialTheme(typography = craneTypography) {
content()
}
}
https://developer.android.com/jetpack/compose/resources
Kotlin 的技術傳教士 - 范聖佑 近期也出了一本關於 Collection 的書 - Kotlin Collection 全方位解析攻略
裡面也有蠻多 operator 的介紹,歡迎大家有興趣的參考看看
https://www.tenlong.com.tw/products/9786263331136