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 HorizontalDivider(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 パラメータは、すべてのアニメーションの終了時に画像を描画する必要があるかどうかを示します。この値を可変の状態で使用した場合、この値を変更すると、対応するアニメーションがトリガーされます。