开源项目 Shopping-By-KMP 使用教程
1. 项目的目录结构及介绍
Shopping-By-KMP 是一个使用 Jetpack Compose Multiplatform 构建的跨平台购物应用程序。项目的目录结构如下:
Shopping-By-KMP/
├── androidApp/
│ ├── src/
│ │ ├── main/
│ │ │ ├── kotlin/
│ │ │ │ ├── com/
│ │ │ │ │ ├── example/
│ │ │ │ │ │ ├── MainActivity.kt
│ ├── build.gradle.kts
├── iosApp/
│ ├── src/
│ │ ├── main/
│ │ │ ├── kotlin/
│ │ │ │ ├── com/
│ │ │ │ │ ├── example/
│ │ │ │ │ │ ├── MainViewController.swift
├── shared/
│ ├── src/
│ │ ├── commonMain/
│ │ │ ├── kotlin/
│ │ │ │ ├── com/
│ │ │ │ │ ├── example/
│ │ │ │ │ │ ├── data/
│ │ │ │ │ │ ├── di/
│ │ │ │ │ │ ├── domain/
│ │ │ │ │ │ ├── presentation/
│ ├── build.gradle.kts
├── build.gradle.kts
├── settings.gradle.kts
├── README.md
目录结构介绍
androidApp/
: 包含 Android 应用程序的源代码和配置文件。src/main/kotlin/com/example/MainActivity.kt
: Android 应用程序的主活动文件。
iosApp/
: 包含 iOS 应用程序的源代码和配置文件。src/main/kotlin/com/example/MainViewController.swift
: iOS 应用程序的主视图控制器文件。
shared/
: 包含共享的跨平台代码。src/commonMain/kotlin/com/example/
: 包含数据、依赖注入、领域和表示层的代码。
build.gradle.kts
: 项目的 Gradle 构建脚本。settings.gradle.kts
: 项目的 Gradle 设置脚本。README.md
: 项目的说明文档。
2. 项目的启动文件介绍
Android 启动文件
在 androidApp/src/main/kotlin/com/example/MainActivity.kt
文件中,定义了 Android 应用程序的主活动:
package com.example
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ShoppingApp()
}
}
}
@Composable
fun ShoppingApp() {
// 应用程序的 UI 代码
}
@Preview
@Composable
fun PreviewShoppingApp() {
ShoppingApp()
}
iOS 启动文件
在 iosApp/src/main/kotlin/com/example/MainViewController.swift
文件中,定义了 iOS 应用程序的主视图控制器:
import UIKit
import SwiftUI
@main
struct ShoppingApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
}
}
3. 项目的配置文件介绍
Gradle 配置文件
build.gradle.kts
: 项目的根级 Gradle 构建脚本,定义了项目的依赖和插件。
plugins {
id("com.android.application")
kotlin("multiplatform")
id("org.jetbrains.compose")
}
repositories {
google()
mavenCentral()
maven("https://maven.