03_Compose资源

2022-12-31  本文已影响0人  刘加城

Compose资源

(1)字符串

    使用stringResource()方法来获取字符串,示例:

// In the res/values/strings.xml file
// <string name="compose">Jetpack Compose</string>

// In your Compose code
Text(
    text = stringResource(R.string.compose)
)

    格式设置:

// 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()方法来获取尺寸,如下:

// 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()方法来获取color,如下:

// In the res/colors.xml file
// <color name="colorGrey">#757575</color>

// In your Compose code
Divider(color = colorResource(R.color.colorGrey))

(4)图片

     使用painterResource()方法来获取图片。不论是矢量图(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)带动画的矢量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)图标Icons

    有5种不同的图标主题:Filled、Outlined、Rounded、TwoTone和Sharp。每个主题包含相同的图标,但是风格不同。使用示例:

import androidx.compose.material.Icon

Icon(Icons.Rounded.Menu, contentDescription = "Localized description")

    有一些常用的图标需要添加material依赖项,如下:

dependencies {
  ...
  implementation "androidx.compose.material:material-icons-extended:$compose_version"
}

(7)字体

    使用Font()方法来加载res/font文件夹下的字体,并创建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 !

上一篇下一篇

猜你喜欢

热点阅读