既存のプロジェクトで Jetpack Compose を使用する場合は、必要な設定と依存関係を指定してプロジェクトを構成する必要があります。
開発環境をセットアップする
適切な Android Studio バージョンをインストールする
Jetpack Compose で最適な開発エクスペリエンスを確保するには、Android Studio をダウンロードし、Android Studio のバージョンに対応する Android Gradle プラグインを設定する必要があります。
buildscript {
...
dependencies {
classpath "com.android.tools.build:gradle:7.0.0"
...
}
}
Kotlin を設定する
プロジェクトで Kotlin 1.6.10 を使用していることを確認します。
plugins {
id 'kotlin-android'
}
Gradle を設定する
以下に示すように、アプリの最小 API レベルを 21 以上に設定し、アプリの build.gradle
ファイルで Jetpack Compose を有効にする必要があります。また、Kotlin コンパイラ プラグインのバージョンも設定します。
android {
defaultConfig {
...
minSdkVersion 21
}
buildFeatures {
// Enables Jetpack Compose for this module
compose true
}
...
// Set both the Java and Kotlin compilers to target Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
composeOptions {
kotlinCompilerExtensionVersion '1.1.1'
}
}
Jetpack Compose ツールキットの依存関係を追加する
以下に示すように、Jetpack Compose ツールキットの依存関係をアプリの build.gradle
ファイルに追加します。
dependencies {
// Integration with activities
implementation 'androidx.activity:activity-compose:1.4.0'
// Compose Material Design
implementation 'androidx.compose.material:material:1.1.1'
// Animations
implementation 'androidx.compose.animation:animation:1.1.1'
// Tooling support (Previews, etc.)
implementation 'androidx.compose.ui:ui-tooling:1.1.1'
// Integration with ViewModels
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1'
// UI Tests
androidTestImplementation 'androidx.compose.ui:ui-test-junit4:1.1.1'
}
Compose でビューテーマを再利用する
Compose をプロジェクトに追加したばかりの場合は、Compose で独自のマテリアル テーマをゼロから書き換えるのではなく、ビューシステムで利用できるテーマを Compose で継承することをおすすめします。
Android アプリで MDC ライブラリを使用している場合、MDC Compose Theme Adapter ライブラリを使用すると、既存の View ベースのテーマにおける色、タイポグラフィ、シェイプのテーマ設定を、コンポーザブルで簡単に再利用できます。これを行うには MdcTheme
API を使用します。
AppCompat XML テーマを使用している場合は、AppCompatTheme
API を含む AppCompat Compose Theme Adapter を使用してください。
以下に示すように、必要な依存関係をアプリの build.gradle
ファイルに追加します。
dependencies {
// When using a MDC theme
implementation "com.google.android.material:compose-theme-adapter:1.1.1"
// When using a AppCompat theme
implementation "com.google.accompanist:accompanist-appcompat-theme:0.16.0"
}
Compose への移行を開始する
アプリ内で、ユーザーの挨拶文のテキストを Jetpack Compose に移行するとします。XML レイアウトには次の内容を追加します。
<...>
<!-- Other content -->
<TextView
android:id="@+id/greeting"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/margin_small"
android:layout_marginEnd="@dimen/margin_small"
android:gravity="center_horizontal"
android:text="@string/greeting"
android:textAppearance="?attr/textAppearanceHeadline5"
... />
</...>
Compose に移行するには、View
を、同じレイアウト パラメータと id
を維持する ComposeView
に置き換えます。
<...>
<!-- Other content -->
<androidx.compose.ui.platform.ComposeView
android:id="@+id/greeting"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</...>
次に、その XML レイアウトを使用する Activity
または Fragment
で、ComposeView
を取得し、setContent
メソッドを呼び出して Compose コンテンツをこの要素に追加します。
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
val greeting = findViewById<ComposeView>(R.id.greeting)
greeting.setContent {
MdcTheme { // or AppCompatTheme
Greeting()
}
}
}
}
@Composable
private fun Greeting() {
Text(
text = stringResource(R.string.greeting),
style = MaterialTheme.typography.h5,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = dimensionResource(R.dimen.margin_small))
.wrapContentWidth(Alignment.CenterHorizontally)
)
}
ComposeView
などの相互運用 API について詳しくは、相互運用 API ガイドをご覧ください。Compose の stringResource
、dimensionResource
などのリソース API について詳しくは、Compose のリソースガイドをご覧ください。
ハイブリッド UI をテストする
アプリの一部を Compose に移行した後は、何も破損していないことをテストで必ず確認する必要があります。
アクティビティまたはフラグメントで Compose が使用される場合、ActivityScenarioRule
を使用する必要がありませんが createAndroidComposeRule
(ActivityScenarioRule
を ComposeTestRule
と統合する)を使用すると、Compose コードと View コードを同時にテストできます。
class MyActivityTest {
@Rule
@JvmField
val composeTestRule = createAndroidComposeRule<MyActivity>()
@Test
fun testGreeting() {
val greeting = InstrumentationRegistry.getInstrumentation()
.targetContext.resources.getString(R.string.greeting)
composeTestRule.onNodeWithText(greeting).assertIsDisplayed()
}
}
テストと Espresso との相互運用について詳しくは、Compose レイアウトのテストガイドをご覧ください。
アーキテクチャで Compose を使用する
Compose はほとんどのアプリ アーキテクチャに対応しており、他の多くの一般的なライブラリと統合できます。そのため、アプリで Compose を使用するにあたり、階層の他のレイヤを変更する必要はありません。
次のコード スニペットは、Compose が viewModel()
関数をアーキテクチャ コンポーネントの ViewModel とともに使用し、collectAsState()
を使用して Kotlin Flow から情報を収集する方法を示しています。
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyScreen()
}
}
}
@Composable
private fun MyScreen(
viewModel: MyViewModel = viewModel()
) {
val uiState by viewModel.uiState.collectAsState()
when {
uiState.isLoading -> { /* ... */ }
uiState.isSuccess -> { /* ... */ }
uiState.isError -> { /* ... */ }
}
}
class MyViewModel : ViewModel() {
private val _uiState = MutableStateFlow(MyScreenState.Loading)
val uiState: StateFlow<MyScreenState> = _uiState
}
画像の読み込み、Paging、Hilt などの統合について詳しくは、Compose とその他のライブラリのガイドをご覧ください。
ナビゲーション
アプリで Navigation コンポーネントを使用している場合は、「Compose を使用したナビゲーション」ガイドの相互運用性に関するセクションをご覧ください。
次のステップ
Compose について詳しくは、ドキュメントのインデックスをご覧ください。アプリに Compose を導入する方法はいくつかあります。詳しくは、アプリへの Compose の導入ガイドをご覧ください。このガイドには、他のガイド(既存のアーキテクチャでの Compose、既存の UI での Compose など)へのリンクもあります。