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 メソッドを使用する際、文字列に数値の文字列形式が含まれる場合は、カウントを 2 回渡す必要があります。たとえば、%1$d minutes という文字列の場合、最初のカウント パラメータが適切な複数形の文字列を選択し、2 つ目のカウント パラメータが %1$d プレースホルダに挿入されます。複数形の文字列に文字列形式が含まれていない場合、3 つ目のパラメータを 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 を段階的に導入する場合は、colorResource API を使用してリソース XML ファイルから色を取得します。

// 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 メソッドを使用して、Image および Icon コンポーザブルで使用できる 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 オブジェクトが用意されています。次の 5 つの異なるアイコンテーマがあります: 塗りつぶし枠線付き円形ツートーン鋭角。各テーマには同じアイコンが含まれていますが、視覚的なスタイルが異なります。一般的には、アプリ全体の整合性を確保するため、1 つのテーマを選択する必要があります。

アイコンを描画するには、Icon コンポーザブルを使用できます。このコンポーザブルは、アイコンに合わせて色合いを適用し、レイアウト サイズを提供します。

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

androidx.compose.material 依存関係の一部として、よく使用されるアイコンの一部を使用できます。その他のマテリアル アイコンを使用するには、build.gradle ファイルに material-icons-extended 依存関係を追加します。

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

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

フォント

Compose でフォントを使用するには、フォント ファイルを res/font フォルダに配置することにより、フォント ファイルを APK に直接ダウンロードしてバンドルします。

Font API を使用して各フォントを読み込み、それらを使用して FontFamily を作成します。これを TextStyle インスタンスで使用することにより、独自の 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 のテーマ設定に関するドキュメントをご覧ください。