412 lines
15 KiB
Markdown
412 lines
15 KiB
Markdown
# KMP Mini Shopping 纯UI离线版(Android)
|
||
|
||
> 用途:课堂一步一步带写 UI,不依赖网络、不依赖 Repository/ViewModel。
|
||
> 方式:直接替换 `composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`。
|
||
|
||
```kotlin
|
||
package com.example.minishop
|
||
|
||
import androidx.compose.foundation.Image
|
||
import androidx.compose.foundation.background
|
||
import androidx.compose.foundation.layout.Arrangement
|
||
import androidx.compose.foundation.layout.Box
|
||
import androidx.compose.foundation.layout.Column
|
||
import androidx.compose.foundation.layout.PaddingValues
|
||
import androidx.compose.foundation.layout.Row
|
||
import androidx.compose.foundation.layout.Spacer
|
||
import androidx.compose.foundation.layout.fillMaxSize
|
||
import androidx.compose.foundation.layout.fillMaxWidth
|
||
import androidx.compose.foundation.layout.height
|
||
import androidx.compose.foundation.layout.padding
|
||
import androidx.compose.foundation.layout.width
|
||
import androidx.compose.foundation.lazy.LazyColumn
|
||
import androidx.compose.foundation.lazy.items
|
||
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
|
||
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
|
||
import androidx.compose.foundation.lazy.staggeredgrid.items as staggeredItems
|
||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||
import androidx.compose.material3.Button
|
||
import androidx.compose.material3.Card
|
||
import androidx.compose.material3.CardDefaults
|
||
import androidx.compose.material3.ElevatedCard
|
||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||
import androidx.compose.material3.MaterialTheme
|
||
import androidx.compose.material3.NavigationBar
|
||
import androidx.compose.material3.NavigationBarItem
|
||
import androidx.compose.material3.OutlinedButton
|
||
import androidx.compose.material3.OutlinedTextField
|
||
import androidx.compose.material3.Scaffold
|
||
import androidx.compose.material3.Surface
|
||
import androidx.compose.material3.Text
|
||
import androidx.compose.material3.TextButton
|
||
import androidx.compose.material3.TopAppBar
|
||
import androidx.compose.runtime.Composable
|
||
import androidx.compose.runtime.getValue
|
||
import androidx.compose.runtime.mutableStateOf
|
||
import androidx.compose.runtime.remember
|
||
import androidx.compose.runtime.setValue
|
||
import androidx.compose.ui.Alignment
|
||
import androidx.compose.ui.Modifier
|
||
import androidx.compose.ui.draw.clip
|
||
import androidx.compose.ui.layout.ContentScale
|
||
import androidx.compose.ui.res.painterResource
|
||
import androidx.compose.ui.text.font.FontWeight
|
||
import androidx.compose.ui.unit.dp
|
||
|
||
enum class Tab { Home, Cart }
|
||
|
||
data class UiProduct(
|
||
val id: String,
|
||
val title: String,
|
||
val price: Double,
|
||
val description: String,
|
||
val imageUrl: String = ""
|
||
)
|
||
|
||
data class UiCartItem(
|
||
val productId: String,
|
||
val quantity: Int
|
||
)
|
||
|
||
@OptIn(ExperimentalMaterial3Api::class)
|
||
@Composable
|
||
fun App() {
|
||
MaterialTheme {
|
||
var currentTab by remember { mutableStateOf(Tab.Home) }
|
||
var inDetail by remember { mutableStateOf(false) }
|
||
var selected by remember { mutableStateOf<UiProduct?>(null) }
|
||
var query by remember { mutableStateOf("") }
|
||
|
||
val products = remember { demoProducts() }
|
||
var cartMap by remember { mutableStateOf<Map<String, Int>>(emptyMap()) }
|
||
|
||
val filtered = remember(products, query) {
|
||
val q = query.trim()
|
||
if (q.isBlank()) products
|
||
else products.filter {
|
||
it.title.contains(q, true) || it.description.contains(q, true)
|
||
}
|
||
}
|
||
|
||
val cartItems = remember(cartMap) {
|
||
cartMap.map { UiCartItem(productId = it.key, quantity = it.value) }
|
||
}
|
||
val productMap = remember(products) { products.associateBy { it.id } }
|
||
val totalCount = cartItems.sumOf { it.quantity }
|
||
val totalPrice = cartItems.sumOf { item ->
|
||
(productMap[item.productId]?.price ?: 0.0) * item.quantity
|
||
}
|
||
|
||
fun add(id: String) {
|
||
cartMap = cartMap.toMutableMap().apply {
|
||
this[id] = (this[id] ?: 0) + 1
|
||
}
|
||
}
|
||
|
||
fun inc(id: String) = add(id)
|
||
|
||
fun dec(id: String) {
|
||
cartMap = cartMap.toMutableMap().apply {
|
||
val old = this[id] ?: return
|
||
if (old <= 1) remove(id) else this[id] = old - 1
|
||
}
|
||
}
|
||
|
||
fun remove(id: String) {
|
||
cartMap = cartMap.toMutableMap().apply { remove(id) }
|
||
}
|
||
|
||
fun clear() {
|
||
cartMap = emptyMap()
|
||
}
|
||
|
||
Scaffold(
|
||
topBar = {
|
||
TopAppBar(
|
||
title = {
|
||
Text(
|
||
when {
|
||
inDetail -> "商品详情"
|
||
currentTab == Tab.Home -> "Mini Shopping(纯UI)"
|
||
else -> "购物车"
|
||
}
|
||
)
|
||
},
|
||
actions = {
|
||
if (inDetail) {
|
||
TextButton(onClick = { inDetail = false }) { Text("返回") }
|
||
} else {
|
||
Text(
|
||
text = "共 $totalCount 件",
|
||
style = MaterialTheme.typography.labelLarge,
|
||
modifier = Modifier.padding(end = 12.dp)
|
||
)
|
||
}
|
||
}
|
||
)
|
||
},
|
||
bottomBar = {
|
||
if (!inDetail) {
|
||
NavigationBar {
|
||
NavigationBarItem(
|
||
selected = currentTab == Tab.Home,
|
||
onClick = { currentTab = Tab.Home },
|
||
icon = { Text("🏠") },
|
||
label = { Text("商品") }
|
||
)
|
||
NavigationBarItem(
|
||
selected = currentTab == Tab.Cart,
|
||
onClick = { currentTab = Tab.Cart },
|
||
icon = { Text("🛒") },
|
||
label = { Text("购物车($totalCount)") }
|
||
)
|
||
}
|
||
}
|
||
}
|
||
) { padding ->
|
||
Box(
|
||
Modifier
|
||
.padding(padding)
|
||
.fillMaxSize()
|
||
.background(MaterialTheme.colorScheme.surface)
|
||
) {
|
||
when {
|
||
inDetail -> DetailScreen(
|
||
product = selected,
|
||
quantity = selected?.let { cartMap[it.id] ?: 0 } ?: 0,
|
||
onAdd = { add(it.id) }
|
||
)
|
||
|
||
currentTab == Tab.Home -> HomeScreen(
|
||
products = filtered,
|
||
totalProducts = products.size,
|
||
query = query,
|
||
quantityOf = { id -> cartMap[id] ?: 0 },
|
||
onQueryChange = { query = it },
|
||
onAdd = { add(it.id) },
|
||
onClick = {
|
||
selected = it
|
||
inDetail = true
|
||
}
|
||
)
|
||
|
||
else -> CartScreen(
|
||
items = cartItems,
|
||
productMap = productMap,
|
||
totalPrice = totalPrice,
|
||
onInc = ::inc,
|
||
onDec = ::dec,
|
||
onRemove = ::remove,
|
||
onClear = ::clear
|
||
)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun HomeScreen(
|
||
products: List<UiProduct>,
|
||
totalProducts: Int,
|
||
query: String,
|
||
quantityOf: (String) -> Int,
|
||
onQueryChange: (String) -> Unit,
|
||
onAdd: (UiProduct) -> Unit,
|
||
onClick: (UiProduct) -> Unit
|
||
) {
|
||
Column(
|
||
Modifier
|
||
.fillMaxSize()
|
||
.padding(12.dp),
|
||
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||
) {
|
||
OutlinedTextField(
|
||
modifier = Modifier.fillMaxWidth(),
|
||
value = query,
|
||
onValueChange = onQueryChange,
|
||
singleLine = true,
|
||
label = { Text("搜索课程") }
|
||
)
|
||
|
||
Text("共 $totalProducts 条 · 当前显示 ${products.size} 条")
|
||
|
||
if (products.isEmpty()) {
|
||
EmptyState("没有匹配的商品")
|
||
} else {
|
||
LazyVerticalStaggeredGrid(
|
||
columns = StaggeredGridCells.Fixed(2),
|
||
verticalItemSpacing = 10.dp,
|
||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||
modifier = Modifier.fillMaxSize()
|
||
) {
|
||
staggeredItems(products, key = { it.id }) { p ->
|
||
ElevatedCard(onClick = { onClick(p) }, modifier = Modifier.fillMaxWidth()) {
|
||
Column(Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
Cover(p.imageUrl)
|
||
Text(p.title, fontWeight = FontWeight.SemiBold)
|
||
PriceTag(p.price)
|
||
Text(p.description, maxLines = 3)
|
||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||
Button(onClick = { onAdd(p) }) { Text("加购") }
|
||
Spacer(Modifier.width(8.dp))
|
||
val q = quantityOf(p.id)
|
||
if (q > 0) Text("x$q", color = MaterialTheme.colorScheme.primary)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun DetailScreen(
|
||
product: UiProduct?,
|
||
quantity: Int,
|
||
onAdd: (UiProduct) -> Unit
|
||
) {
|
||
if (product == null) {
|
||
EmptyState("商品不存在")
|
||
return
|
||
}
|
||
|
||
Column(
|
||
Modifier
|
||
.fillMaxSize()
|
||
.padding(16.dp),
|
||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||
) {
|
||
Cover(product.imageUrl)
|
||
Text(product.title, style = MaterialTheme.typography.headlineSmall)
|
||
PriceTag(product.price)
|
||
Text(product.description)
|
||
if (quantity > 0) Text("当前已加购:$quantity")
|
||
Button(onClick = { onAdd(product) }, modifier = Modifier.fillMaxWidth()) {
|
||
Text("加入购物车")
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun CartScreen(
|
||
items: List<UiCartItem>,
|
||
productMap: Map<String, UiProduct>,
|
||
totalPrice: Double,
|
||
onInc: (String) -> Unit,
|
||
onDec: (String) -> Unit,
|
||
onRemove: (String) -> Unit,
|
||
onClear: () -> Unit
|
||
) {
|
||
Box(
|
||
Modifier
|
||
.fillMaxSize()
|
||
.padding(horizontal = 16.dp, vertical = 12.dp)
|
||
) {
|
||
if (items.isEmpty()) {
|
||
EmptyState("购物车为空")
|
||
} else {
|
||
LazyColumn(
|
||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||
contentPadding = PaddingValues(bottom = 96.dp)
|
||
) {
|
||
items(items) { item ->
|
||
val p = productMap[item.productId] ?: return@items
|
||
Card(Modifier.fillMaxWidth()) {
|
||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||
Text(p.title)
|
||
Text("¥${formatPrice(p.price * item.quantity)}")
|
||
}
|
||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||
OutlinedButton(onClick = { onDec(p.id) }) { Text("-") }
|
||
Text(" ${item.quantity} ")
|
||
OutlinedButton(onClick = { onInc(p.id) }) { Text("+") }
|
||
Spacer(Modifier.width(8.dp))
|
||
OutlinedButton(onClick = { onRemove(p.id) }) { Text("移除") }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
Card(
|
||
modifier = Modifier
|
||
.align(Alignment.BottomCenter)
|
||
.fillMaxWidth(),
|
||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer)
|
||
) {
|
||
Row(
|
||
modifier = Modifier
|
||
.fillMaxWidth()
|
||
.padding(12.dp),
|
||
horizontalArrangement = Arrangement.SpaceBetween,
|
||
verticalAlignment = Alignment.CenterVertically
|
||
) {
|
||
Column {
|
||
Text("总件数:${items.sumOf { it.quantity }}")
|
||
Text("合计:¥${formatPrice(totalPrice)}", fontWeight = FontWeight.Bold)
|
||
}
|
||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||
OutlinedButton(onClick = onClear) { Text("清空") }
|
||
Button(onClick = onClear) { Text("结算(模拟)") }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun Cover(url: String) {
|
||
// 纯UI课:不走网络图,直接本地占位
|
||
Image(
|
||
painter = painterResource(id = R.drawable.course_cover_default),
|
||
contentDescription = null,
|
||
modifier = Modifier
|
||
.fillMaxWidth()
|
||
.height(150.dp)
|
||
.clip(RoundedCornerShape(12.dp)),
|
||
contentScale = ContentScale.Crop
|
||
)
|
||
}
|
||
|
||
@Composable
|
||
private fun PriceTag(price: Double) {
|
||
Surface(
|
||
color = MaterialTheme.colorScheme.primaryContainer,
|
||
shape = RoundedCornerShape(10.dp)
|
||
) {
|
||
Text(
|
||
text = "¥${formatPrice(price)}",
|
||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
|
||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||
fontWeight = FontWeight.SemiBold
|
||
)
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun EmptyState(text: String) {
|
||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||
Text("🧺")
|
||
Spacer(Modifier.height(8.dp))
|
||
Text(text)
|
||
}
|
||
}
|
||
}
|
||
|
||
private fun formatPrice(price: Double): String = "%.2f".format(price)
|
||
|
||
private fun demoProducts(): List<UiProduct> = listOf(
|
||
UiProduct("1", "KMP 入门课", 99.0, "跨平台开发基础课程"),
|
||
UiProduct("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战"),
|
||
UiProduct("3", "协程训练营", 129.0, "协程与 Flow 进阶"),
|
||
UiProduct("4", "Clean 架构速成", 199.0, "从0构建可维护架构"),
|
||
UiProduct("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案"),
|
||
UiProduct("6", "Ktor API 实战", 159.0, "跨平台网络层搭建")
|
||
)
|
||
```
|