如果想在現有專案中使用 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 工具包依附元件
在應用程式的 build.gradle
檔案中加入 Jetpack Compose 工具包,如下所示:
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 繼承 View 系統中提供的主題,而不是在 Compose 中從頭開始重寫自己的材質主題。
在 Android 應用程式中使用 MDC 程式庫時,MDC Compose Theme 轉接程式程式庫可讓您在可組合項中輕鬆重複使用基於檢視畫面的現有主題中的色彩、字型樣式和形狀主題。方法是使用 MdcTheme
API。
如果您改為使用 AppCompat XML 主題,請使用包含 AppCompatTheme
API 的 AppCompat Compose Theme 轉接程式。
在應用程式的 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
替換為 ComposeView
,並保留相同的版面配置參數和 id
:
<...>
<!-- Other content -->
<androidx.compose.ui.platform.ComposeView
android:id="@+id/greeting"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</...>
接著,在 Activity
或 Fragment
使用該 XML 版面配置,就會獲得 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,請參閱 Interoperability API 指南。如要進一步瞭解 Compose 中的 stringResource
、dimensionResource
及其他資源 API,請參閱Compose 指南中的資源。
測試混合型使用者介面
將應用程式的某個部分遷移至 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 功能,就不需要變更其他等級層。
下列程式碼片段顯示如何使用 viewModel()
函式將 Compose 與架構元件 ViewModels 搭配使用,以及使用 collectAsState()
從 Kotlin 流收集。
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
}
如需更多有關圖片載入、分頁或 Hilt 的整合資訊,請參閱 Compose 及其他程式庫指南。
導航
如要在應用程式中使用導航元件,請參閱 Compose 導航使用指南中的互通性部分。
後續步驟
如要進一步瞭解 Compose,請參閱文件索引。您可以透過不同方法在應用程式中加入 Compose,詳情請參閱在應用程式中採用 Compose 的相關指南。這份指南還可以連結至其他指南,例如現有架構中的 Compose 以及現有使用者介面中的 Compose。