Compose의 리소스

Jetpack Compose는 Android 프로젝트에 정의된 리소스에 액세스할 수 있습니다. 이 문서에서는 이를 위해 Compose에서 제공하는 API를 설명합니다.

리소스는 코드에서 사용하는 추가 파일과 정적인 콘텐츠입니다. 예를 들어 비트맵, 레이아웃 정의, 사용자 인터페이스 문자열, 애니메이션 지침 등이 있습니다. Android의 리소스에 익숙하지 않은 경우 앱 리소스 개요 가이드를 확인하세요.

문자열

가장 일반적인 리소스 유형은 문자열입니다. XML 리소스에 정적으로 정의된 문자열을 가져오려면 stringResource API를 사용하세요.

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

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

stringResource는 위치 형식과 함께 사용할 수도 있습니다.

// 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)
)

문자열 복수형(실험용)

pluralStringResource API를 사용하여 특정 수량과 함께 복수형을 로드합니다.

// In the res/strings.xml file
// <plurals name="runtime_format">
//    <item quantity="one">%1$d minute</item>
//    <item quantity="other">%1$d minutes</item>
// </plurals>

// In your Compose code
Text(
    text = pluralStringResource(
        R.plurals.runtime_format,
        quantity,
        quantity
    )
)

pluralStringResource 메서드를 사용하는 경우 문자열에 숫자로 형식이 지정된 문자열이 포함되어 있다면 개수를 두 번 전달해야 합니다. 예를 들어 문자열 %1$d minutes의 경우 첫 번째 count 매개변수는 적절한 복수형 문자열을 선택하고, 두 번째 count 매개변수는 %1$d 자리표시자에 삽입됩니다. 복수형 문자열에 문자열 형식이 포함되지 않은 경우 세 번째 매개변수를 pluralStringResource에 전달할 필요가 없습니다.

복수형에 관한 자세한 내용은 수량 문자열 문서를 참고하세요.

크기

마찬가지로 리소스 XML 파일에서 크기를 가져오려면 dimensionResource API를 사용하세요.

// 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)
)

색상

앱에서 Compose를 점진적으로 채택하는 경우 리소스 XML 파일에서 색상을 가져오려면 colorResource API를 사용하세요.

// In the res/colors.xml file
// <color name="purple_200">#FFBB86FC</color>

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

colorResource는 정적 색상을 사용하여 예상대로 작동하지만 색상 상태 목록 리소스를 평면화합니다.

벡터 애셋 및 이미지 리소스

벡터 드로어블 또는 PNG와 같이 래스터화된 애셋 형식을 로드하려면 painterResource API를 사용하세요. 드로어블의 유형을 알 필요가 없습니다. Image 컴포저블 또는 paint 제어자에 painterResource를 사용하면 됩니다.

// 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
)

painterResource는 기본 스레드의 리소스 콘텐츠를 디코딩하고 파싱합니다.

애니메이션 벡터 드로어블

애니메이션 벡터 드로어블 XML을 로드하려면 AnimatedImageVector.animatedVectorResource API를 사용하세요. 이 메서드는 AnimatedImageVector 인스턴스를 반환합니다. 애니메이션 이미지를 표시하려면 rememberAnimatedVectorPainter 메서드를 사용하여 ImageIcon 컴포저블에서 사용할 수 있는 Painter를 만드세요. rememberAnimatedVectorPainter 메서드의 부울 atEnd 매개변수는 모든 애니메이션의 끝부분에 이미지를 그려야 하는지 여부를 나타냅니다. 변경 가능한 상태와 함께 사용하는 경우 이 값을 변경하면 상응하는 애니메이션이 트리거됩니다.

// Files in res/drawable folders. For example:
// - res/drawable/ic_hourglass_animated.xml

// In your Compose code
val image =
    AnimatedImageVector.animatedVectorResource(R.drawable.ic_hourglass_animated)
val atEnd by remember { mutableStateOf(false) }
Icon(
    painter = rememberAnimatedVectorPainter(image, atEnd),
    contentDescription = null // decorative element
)

아이콘

Jetpack Compose에는 Compose에서 머티리얼 아이콘을 사용하기 위한 진입점인 Icons 객체가 함께 제공됩니다. Filled, Outlined, Rounded, TwoTone, Sharp 등 다섯 가지의 고유한 아이콘 테마가 있습니다. 각 테마에는 동일한 아이콘이 고유한 시각적 스타일과 함께 포함되어 있습니다. 일반적으로 일관성을 유지하기 위해 하나의 테마를 선택하여 애플리케이션 전체에서 사용해야 합니다.

아이콘을 그리려면 색조를 적용하고 아이콘과 일치하는 레이아웃 크기를 제공하는 Icon 컴포저블을 사용하세요.

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

가장 일반적으로 사용되는 아이콘 중 일부는 androidx.compose.material 종속 항목의 일부로 사용할 수 있습니다. 다른 머티리얼 아이콘을 사용하려면 material-icons-extended 종속 항목을 build.gradle 파일에 추가하세요.

dependencies {
  def composeBom = platform('androidx.compose:compose-bom:2024.04.00')
  implementation composeBom

  implementation 'androidx.compose.material:material-icons-extended'
}

글꼴

Compose에서 글꼴을 사용하려면 글꼴 파일을 APK에 직접 다운로드한 후 res/font 폴더에 배치하여 번들로 묶습니다.

Font API를 사용하여 각 글꼴을 로드하고 이 글꼴로 TextStyle 인스턴스에서 사용할 수 있는 FontFamily를 만들어 고유한 Typography를 만듭니다. 다음은 Crane Compose 샘플 및 Typography.kt 파일에서 가져온 코드입니다.

// 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(
    titleLarge = TextStyle(
        fontFamily = 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()
    }
}

Compose에서 다운로드 가능한 글꼴을 사용하는 방법은 다운로드 가능한 글꼴 페이지를 참고하세요.

서체에 관한 자세한 내용은 Compose의 테마 설정 문서를 참고하세요.