Kotlin Multiplatform(KMP)结合 Compose Multiplatform 正在成为跨平台开发的热门选择,它允许开发者用一套代码构建 Android、iOS、桌面(Windows/macOS/Linux)和 Web 应用。以下是一个实战指南,涵盖核心概念和代码示例。
gradle.properties
:kotlin.native.cacheKind=none # 避免 iOS 编译缓存问题典型的多平台项目结构:
shared/
src/
commonMain/ # 公共代码(Compose UI、业务逻辑)
androidMain/ # Android 平台特定代码
iosMain/ # iOS 平台特定代码
desktopMain/ # 桌面端代码
androidApp/ # Android 应用模块
iosApp/ # iOS Xcode 项目
desktopApp/ # 桌面端启动模块
在 shared/src/commonMain/kotlin
中创建跨平台组件:
// 共享的 Compose 组件
@Composable
fun Greeting(name: String) {
Text(
text = "Hello, $name!",
modifier = Modifier.padding(16.dp),
color = Color.Blue
)
}
// 平台无关的 ViewModel
class SharedViewModel {
private val _count = mutableStateOf(0)
val count: State<Int> = _count
fun increment() {
_count.value++
}
}
androidApp
模块)直接使用 Compose:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AppTheme { // 自定义主题
Greeting("Android")
}
}
}
}
iosApp
模块)通过 UIViewController
嵌入 Compose:
// shared/src/iosMain/kotlin
fun MainViewController(): UIViewController =
ComposeUIViewController {
Greeting("iOS")
}
desktopApp
模块)fun main() = application {
Window(onCloseRequest = ::exitApplication) {
Greeting("Desktop")
}
}
使用 expect/actual
机制实现平台特定逻辑:
// 公共代码声明 expect
expect fun getPlatformName(): String
// Android 实现
actual fun getPlatformName(): String = "Android"
// iOS 实现
actual fun getPlatformName(): String = "iOS"
在 Compose 中使用:
@Composable
fun PlatformSpecificGreeting() {
Text("Running on ${getPlatformName()}")
}
mutableStateOf
或 ViewModel(通过 koin
或 kodein
注入)。@Composable
fun App() {
var currentScreen by remember { mutableStateOf<Screen>(Screen.Home) }
when (currentScreen) {
is Screen.Home -> HomeScreen { currentScreen = Screen.Detail }
is Screen.Detail -> DetailScreen { currentScreen = Screen.Home }
}
}
commonMain/resources
,通过路径访问:Image(painterResource("images/logo.png"), "logo")androidMain/resources
或 iosMain/resources
放置平台特定资源。./gradlew podGen
iosApp/iosApp.xcworkspace
并运行。./gradlew run
或打包为原生应用:./gradlew packageDebian # Linux
./gradlew packageMsi # Windows
./gradlew packageDmg # macOSgradle.properties
中设置 kotlin.native.cacheKind=none
)。NSDataAsset
)。通过 Compose Multiplatform,开发者可以显著减少重复代码,但需注意平衡代码共享与平台体验。建议从简单模块开始逐步迁移,同时利用 Kotlin 的强类型特性减少运行时错误。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有