Compose資源
(1)字符串
????使用stringResource()方法來(lái)獲取字符串,示例:
// In the res/values/strings.xml file
// <string name="compose">Jetpack Compose</string>
// In your Compose code
Text(
text = stringResource(R.string.compose)
)
????格式設(shè)置:
// In the res/values/strings.xml file
// <string name="congratulate">Happy %1$s %2$d</string>
// In your Compose code
Text(
text = stringResource(R.string.congratulate, "New Year", 2021)
)
(2)尺寸Dimension
????使用dimensionResource()方法來(lái)獲取尺寸,如下:
// In the res/values/dimens.xml file
// <dimen name="padding_small">8dp</dimen>
// In your Compose code
val smallPadding = dimensionResource(R.dimen.padding_small)
Text(
text = "...",
modifier = Modifier.padding(smallPadding)
)
(3)顏色Colors
???? 使用colorResource()方法來(lái)獲取color,如下:
// In the res/colors.xml file
// <color name="colorGrey">#757575</color>
// In your Compose code
Divider(color = colorResource(R.color.colorGrey))
(4)圖片
???? 使用painterResource()方法來(lái)獲取圖片。不論是矢量圖(SVG),還是位圖(png、jpg、webP等),都可以。示例如下:
// Files in res/drawable folders. For example:
// - res/drawable-nodpi/ic_logo.xml
// - res/drawable-xxhdpi/ic_logo.png
// In your Compose code
Icon(
painter = painterResource(id = R.drawable.ic_logo),
contentDescription = null // decorative element
)
(5)帶動(dòng)畫(huà)的矢量Drawable
????示例:
// Files in res/drawable folders. For example:
// - res/drawable/animated_vector.xml
// In your Compose code
val image = AnimatedImageVector.animatedVectorResource(R.drawable.animated_vector)
val atEnd by remember { mutableStateOf(false) }
Icon(
painter = rememberAnimatedVectorPainter(image, atEnd),
contentDescription = null // decorative element
)
(6)圖標(biāo)Icons
????有5種不同的圖標(biāo)主題:Filled、Outlined、Rounded、TwoTone和Sharp。每個(gè)主題包含相同的圖標(biāo),但是風(fēng)格不同。使用示例:
import androidx.compose.material.Icon
Icon(Icons.Rounded.Menu, contentDescription = "Localized description")
????有一些常用的圖標(biāo)需要添加material依賴(lài)項(xiàng),如下:
dependencies {
...
implementation "androidx.compose.material:material-icons-extended:$compose_version"
}
(7)字體
????使用Font()方法來(lái)加載res/font文件夾下的字體,并創(chuàng)建FontFamily,然后使用它。示例:
// 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()
}
}
????Over !