1. @Composable 函数基础

// 最简单的Composable函数
@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

// 在Activity中使用
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyAppTheme {  // 应用主题
                Greeting("Android")
            }
        }
    }
}

// Composable函数可以调用其他Composable函数
@Composable
fun WelcomeScreen() {
    Column {
        Greeting("张三")
        Greeting("李四")
    }
}

2. 基础组件:Text, Button, Column, Row

@Composable
fun BasicComponents() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // Text组件
        Text(
            text = "标题文本",
            fontSize = 24.sp,
            fontWeight = FontWeight.Bold,
            color = Color.Blue
        )
        
        Text("普通文本内容")
        
        // Button组件
        Button(
            onClick = { /* 点击事件 */ },
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.Green
            )
        ) {
            Text("点击按钮")
        }
        
        // Row:水平排列
        Row(
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Button(onClick = { }) { Text("按钮1") }
            Button(onClick = { }) { Text("按钮2") }
        }
        
        // 嵌套布局
        Card(
            modifier = Modifier.fillMaxWidth(),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text("卡片标题", fontWeight = FontWeight.Bold)
                Text("卡片内容描述")
            }
        }
    }
}

 3. 状态管理:remember, mutableStateOf

@Composable
fun CounterExample() {
    // 状态变量:记住组件重组间的数据
    var count by remember { mutableStateOf(0) }
    
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.padding(16.dp)
    ) {
        Text(
            text = "计数: $count",
            fontSize = 32.sp,
            fontWeight = FontWeight.Bold
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(onClick = { count-- }) {
                Text("-")
            }
            
            Button(onClick = { count++ }) {
                Text("+")
            }
            
            Button(onClick = { count = 0 }) {
                Text("重置")
            }
        }
    }
}

// 多个状态管理
@Composable
fun UserInfoForm() {
    var name by remember { mutableStateOf("") }
    var age by remember { mutableStateOf("") }
    var isVisible by remember { mutableStateOf(true) }
    
    Column(modifier = Modifier.padding(16.dp)) {
        // 文本输入
        OutlinedTextField(
            value = name,
            onValueChange = { name = it },
            label = { Text("姓名") },
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        OutlinedTextField(
            value = age,
            onValueChange = { age = it },
            label = { Text("年龄") },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 显示/隐藏控制
        Row(verticalAlignment = Alignment.CenterVertically) {
            Checkbox(
                checked = isVisible,
                onCheckedChange = { isVisible = it }
            )
            Text("显示用户信息")
        }
        
        // 条件显示
        if (isVisible && name.isNotEmpty()) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text("用户信息:", fontWeight = FontWeight.Bold)
                    Text("姓名: $name")
                    if (age.isNotEmpty()) {
                        Text("年龄: $age")
                    }
                }
            }
        }
    }
}

4. 事件处理:点击、输入

@Composable
fun EventHandlingExample() {
    var message by remember { mutableStateOf("点击按钮试试") }
    var inputText by remember { mutableStateOf("") }
    var selectedOption by remember { mutableStateOf("选项1") }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 显示消息
        Text(
            text = message,
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.LightGray, RoundedCornerShape(8.dp))
                .padding(16.dp)
        )
        
        // 点击事件
        Button(
            onClick = { 
                message = "按钮被点击了!时间: ${System.currentTimeMillis()}"
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("点击我")
        }
        
        // 长按事件
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(60.dp)
                .background(Color.Blue, RoundedCornerShape(8.dp))
                .clickable { message = "Box被点击" }
                .pointerInput(Unit) {
                    detectTapGestures(
                        onLongPress = { message = "Box被长按了" }
                    )
                },
            contentAlignment = Alignment.Center
        ) {
            Text("点击或长按这个区域", color = Color.White)
        }
        
        // 文本输入事件
        OutlinedTextField(
            value = inputText,
            onValueChange = { newValue ->
                inputText = newValue
                message = "输入内容: $newValue"
            },
            label = { Text("输入文本") },
            modifier = Modifier.fillMaxWidth()
        )
        
        // 单选按钮
        val options = listOf("选项1", "选项2", "选项3")
        Text("选择一个选项:")
        Column {
            options.forEach { option ->
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable {
                        selectedOption = option
                        message = "选择了: $option"
                    }
                ) {
                    RadioButton(
                        selected = selectedOption == option,
                        onClick = {
                            selectedOption = option
                            message = "选择了: $option"
                        }
                    )
                    Text(text = option)
                }
            }
        }
    }
}

综合练习:计数器App

@Composable
fun CounterApp() {
    var count by remember { mutableStateOf(0) }
    var step by remember { mutableStateOf(1) }
    var history by remember { mutableStateOf(listOf<String>()) }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 显示当前计数
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(containerColor = Color.LightBlue)
        ) {
            Text(
                text = count.toString(),
                fontSize = 48.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(32.dp),
                textAlign = TextAlign.Center
            )
        }
        
        // 步长设置
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text("步长: ")
            Button(onClick = { if (step > 1) step-- }) { Text("-") }
            Text(" $step ", modifier = Modifier.padding(horizontal = 16.dp))
            Button(onClick = { step++ }) { Text("+") }
        }
        
        // 操作按钮
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(
                onClick = { 
                    count -= step
                    history = history + "减少 $step"
                }
            ) { Text("- $step") }
            
            Button(
                onClick = { 
                    count = 0
                    history = history + "重置为 0"
                }
            ) { Text("重置") }
            
            Button(
                onClick = { 
                    count += step
                    history = history + "增加 $step"
                }
            ) { Text("+ $step") }
        }
        
        // 操作历史
        if (history.isNotEmpty()) {
            Text("操作历史:", fontWeight = FontWeight.Bold)
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp)
            ) {
                items(history.takeLast(10)) { item ->
                    Text(
                        text = "• $item",
                        modifier = Modifier.padding(vertical = 2.dp)
                    )
                }
            }
            
            Button(
                onClick = { history = emptyList() },
                colors = ButtonDefaults.buttonColors(containerColor = Color.Red)
            ) {
                Text("清空历史")
            }
        }
    }
}

每日练习建议

第1-3天: 基础组件熟悉

  • 创建不同样式的Text和Button
  • 练习Column和Row的排列组合

第4-7天: 状态管理练习

  • 做一个简单的开关控制器
  • 实现一个简单的表单

第8-14天: 事件处理和综合应用

  • 制作一个简单的计算器
  • 做一个TodoList的添加功能

学习要点:

  • 理解重组(Recomposition)概念
  • 状态提升(State Hoisting)原则
  • 合理使用remember避免不必要的重组
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐