Android 与 Compose
Jetpack、Compose Multiplatform 直觉。
30 分钟
Android 与 Compose
Kotlin 是 Android 官方首选语言;Jetpack Compose 用声明式 UI 替代 XML 布局,Kotlin Multiplatform 可共享业务逻辑。
学习目标
- 了解 Android 项目中的 Kotlin 结构
- 理解 Jetpack Compose 的基本组件与状态
- 知道 Compose Multiplatform 的跨平台直觉
Android 项目结构
app/
src/main/
java/com/example/app/
MainActivity.kt ← Activity 入口
ui/
theme/ ← Material 主题
screens/ ← Compose 界面
res/ ← 资源( drawable、values)
build.gradle.kts
MainActivity 继承 ComponentActivity,setContent { } 挂载 Compose 根节点。
Compose 基础
@Composable
fun LessonCard(slug: String, title: String, onClick: () -> Unit) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
.clickable(onClick = onClick),
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(text = title, style = MaterialTheme.typography.titleMedium)
Text(text = slug, style = MaterialTheme.typography.bodySmall)
}
}
}
@Composable
fun LessonList(lessons: List<Pair<String, String>>) {
LazyColumn {
items(lessons) { (slug, title) ->
LessonCard(slug = slug, title = title, onClick = { })
}
}
}
@Composable 函数描述 UI;LazyColumn 类似 RecyclerView 的懒加载列表。
状态与 ViewModel
@Composable
fun TrackScreen(viewModel: TrackViewModel = viewModel()) {
val lessons by viewModel.lessons.collectAsState()
Column(modifier = Modifier.fillMaxSize()) {
Text("Kotlin 语言入门", style = MaterialTheme.typography.headlineMedium)
LessonList(lessons = lessons)
}
}
class TrackViewModel : ViewModel() {
private val _lessons = MutableStateFlow<List<Pair<String, String>>>(emptyList())
val lessons: StateFlow<List<Pair<String, String>>> = _lessons.asStateFlow()
init {
_lessons.value = listOf(
"kt-intro" to "Kotlin 是什么",
"kt-syntax" to "基础语法"
)
}
}
StateFlow + collectAsState 实现响应式 UI;ViewModel survive 配置变更。