当前位置: 首页 > news >正文

Android中Compose常用组件以及布局使用方法

一、基础控件详解

1. Text - 文本控件
Text(text = "Hello Compose", // 必填,显示文本color = Color.Blue,      // 文字颜色fontSize = 24.sp,        // 字体大小(注意使用.sp单位)fontStyle = FontStyle.Italic, // 字体样式(斜体)fontWeight = FontWeight.Bold, // 字体粗细modifier = Modifier.padding(16.dp)     // 内边距.background(Color.LightGray) // 背景色
)

核心参数说明

  • text:显示的文字内容(必填

  • color:文字颜色(Color.RedColor(0xFF6200EE)等)

  • fontSize:字体大小(必须使用.sp单位,如18.sp

  • fontWeight:字体粗细(FontWeight.NormalBoldW800等)

  • modifier:通用修饰符(设置边距、背景、点击事件等)

  • maxLines:最大行数(超出显示省略号)

  • textDecoration:文本装饰(TextDecoration.Underline下划线)

效果(示意图)

[浅灰色背景]Hello Compose(蓝色,24sp,粗体,斜体)

2. Button - 按钮控件
val context = LocalContext.currentButton(onClick = { // 必填,点击回调Toast.makeText(context, "Clicked!", Toast.LENGTH_SHORT).show()},colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red, // 按钮背景contentColor = Color.White   // 内容颜色),modifier = Modifier.padding(8.dp),enabled = true // 是否启用
) {Icon( // 图标imageVector = Icons.Filled.Favorite,contentDescription = "Like")Spacer(Modifier.width(8.dp)) // 间距Text("Like") // 按钮文字
}

核心参数说明

  • onClick:点击事件回调(必填

  • colors:颜色配置(背景色、文字色)

  • enabled:是否启用(false时变灰色)

  • content:按钮内容(可包含任意Composable)

效果

[红色按钮] ♥ Like(白色文字)
点击后弹出Toast

3. TextField - 输入框控件
var text by remember { mutableStateOf("") } // 关键:状态管理TextField(value = text, // 当前值(绑定状态)onValueChange = { newText -> // 输入变化回调text = newText },label = { Text("Username") }, // 浮动标签placeholder = { Text("Enter your name") }, // 提示文字leadingIcon = { // 前缀图标Icon(Icons.Filled.Person, null) },keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, // 键盘类型imeAction = ImeAction.Done        // 键盘动作),modifier = Modifier.fillMaxWidth()
)

核心参数说明

  • value/onValueChange必须配合状态管理remember+mutableStateOf

  • label:浮动标签(输入时上浮)

  • placeholder:提示文本(未输入时显示)

  • keyboardOptions:键盘配置(邮箱/数字键盘等)

  • singleLine:是否单行(true时禁用换行)


4. Image - 图片控件
// 加载本地资源
Image(painter = painterResource(R.drawable.dog),contentDescription = "Cute dog", // 必填(无障碍)modifier = Modifier.size(120.dp).clip(CircleShape), // 圆形裁剪contentScale = ContentScale.Crop // 裁剪模式
)// 加载网络图片(Coil)
AsyncImage(model = "https://example.com/image.jpg",contentDescription = "Network image",placeholder = { // 加载中显示CircularProgressIndicator()},error = { // 错误显示Icon(Icons.Filled.Error, null)}
)

核心参数说明

  • painter:本地资源(painterResource()

  • contentDescription必填(无障碍支持)

  • contentScale:缩放模式(CropFitInside等)

  • alpha:透明度(0.0f-1.0f)

  • colorFilter:颜色滤镜(如黑白效果)


5. ProgressIndicator - 进度指示器
// 圆形进度条
CircularProgressIndicator(progress = 0.7f, // 进度值(0-1)color = Color.Green,strokeWidth = 8.dp,modifier = Modifier.size(50.dp)
)// 线性进度条
LinearProgressIndicator(progress = 0.4f,backgroundColor = Color.LightGray,color = MaterialTheme.colors.primary,modifier = Modifier.fillMaxWidth().padding(16.dp)
)

参数说明

  • progress:进度值(0-1),不传则为不确定进度

  • color:进度条颜色

  • strokeWidth:圆形进度条粗细

  • backgroundColor:线性进度条背景色


二、核心布局详解(附结构图)

1. Column - 垂直布局
Column(modifier = Modifier.fillMaxSize() // 占满父布局.background(Color.LightGray),horizontalAlignment = Alignment.CenterHorizontally, // 水平居中verticalArrangement = Arrangement.SpaceEvenly // 等间距分布
) {Text("Item 1")Button(onClick = {}) { Text("Button") }Image(painterResource(R.drawable.icon), null)
}

参数说明

参数说明常用值
horizontalAlignment子项水平对齐StartCenterHorizontallyEnd
verticalArrangement垂直分布方式TopCenterSpaceBetweenSpaceEvenly
modifier修饰符设置尺寸/背景/边距等

布局效果

┌───────────────────────────┐
│                           │
│          Item 1           │
│                           │
│         [ Button ]        │
│                           │
│          [图标]           │
│                           │
└───────────────────────────┘
(等间距分布)

2. Row - 水平布局
Row(modifier = Modifier.fillMaxWidth().background(Color.LightGray).padding(16.dp).horizontalScroll(rememberScrollState()), // 水平滚动verticalAlignment = Alignment.CenterVertically, // 垂直居中horizontalArrangement = Arrangement.SpaceBetween // 两端对齐
) {Icon(Icons.Filled.Menu, "Menu")Text("Title", fontWeight = FontWeight.Bold)Icon(Icons.Filled.Search, "Search")
}

参数说明

参数说明常用值
verticalAlignment子项垂直对齐TopCenterVerticallyBottom
horizontalArrangement水平分布方式StartCenterSpaceBetweenSpaceAround
.horizontalScroll()水平滚动支持必须添加

布局效果

┌─[菜单]─────标题─────[搜索]─┐
(两端对齐,可横向滚动)

3. Box - 层叠布局
Box(modifier = Modifier.size(200.dp).background(Color.Blue)
) {Image( // 底层painter = painterResource(R.drawable.bg),contentDescription = "Background",modifier = Modifier.fillMaxSize())Text( // 中层"Overlay Text",color = Color.White,modifier = Modifier.align(Alignment.Center).padding(8.dp))Button( // 顶层onClick = {},modifier = Modifier.align(Alignment.BottomEnd).padding(16.dp)) {Text("Action")}
}

关键方法

  • Modifier.align():在Box内定位

    • Alignment.TopStart

    • Alignment.Center

    • Alignment.BottomEnd

  • Modifier.zIndex():控制层级(默认后添加的在上层)

布局效果

┌───────────────────────────┐
│   [背景图片]              │
│                           │
│        居中文字           │
│                           │
│                   [按钮]  │
└───────────────────────────┘
(三层叠加)

三、常见问题

Q1:Compose 为什么需要状态管理?TextField 如何处理状态变化?

// 状态声明
var text by remember { mutableStateOf("") }// 状态绑定
TextField(value = text, // 绑定状态值onValueChange = { newText -> text = newText // 更新状态}
)/*
1. 初始状态 text = ""
2. 用户输入 "A" -> 触发 onValueChange
3. text 更新为 "A"
4. 状态变化触发重组(Recomposition)
5. TextField 根据新值刷新界面
*/
Q2:如何实现列表滚动?

垂直滚动

Column(modifier = Modifier.verticalScroll(rememberScrollState())
) { /* 长内容 */ }

高性能列表(LazyColumn)

LazyColumn {item { Header() }items(100) { index -> // 只渲染可见项ListItem(index)}item { Footer() }
}
Q3:Box 布局如何实现复杂定位?
Box(modifier = Modifier.fillMaxSize()) {// 左上角Text("TopStart", Modifier.align(Alignment.TopStart))// 右上角Button(onClick = {}, Modifier.align(Alignment.TopEnd)) { ... }// 正中央Image(..., Modifier.align(Alignment.Center))// 左下角Icon(..., Modifier.align(Alignment.BottomStart))// 右下角CircularProgressIndicator(Modifier.align(Alignment.BottomEnd))
}
Q4:如何实现响应式布局?
@Composable
fun AdaptiveLayout() {// 根据屏幕宽度选择布局val configuration = LocalConfiguration.currentval screenWidth = configuration.screenWidthDp.dpif (screenWidth < 600.dp) {VerticalLayout() // 小屏:垂直布局} else {HorizontalLayout() // 大屏:水平布局}
}

http://www.lqws.cn/news/579547.html

相关文章:

  • 深入解析TCP:可靠传输的核心机制与实现逻辑
  • 首次使用“非英伟达”芯片!OpenAI租用谷歌TPU,降低推理计算成本
  • 成像光谱遥感技术中的AI革命:ChatGPT在遥感领域中的应用
  • (LeetCode 每日一题) 594. 最长和谐子序列 (哈希表)
  • redis相关内容以及安全知识
  • 开疆智能CCLinkIE转Canopen网关连接UV紫外灯配置案例
  • python包管理工具uv VS pip
  • iOS 接口频繁请求导致流量激增?抓包分析定位与修复全流程
  • 人工智能和云计算对金融未来的影响
  • 力扣 hot100 Day30
  • 键盘第一下无反应
  • Armbian 25.5.1 Noble Gnome 开启远程桌面功能
  • CMake中WIN32和CMAKE_HOST_WIN32的使用差异
  • Pytest pytest_runtest_makereport 钩子函数:测试失败信息收集与处理 —— Python 实践
  • (5)pytest-yield操作
  • Python量化金融:从数据到策略的工程实现
  • Serverless 架构入门与实战:AWS Lambda、Azure Functions、Cloudflare Workers 对比
  • CH32H417 替代 Cypress FX3 及优势探讨
  • RF100:多领域目标检测基准数据集(猫脸码客第284期)
  • Ubuntu更换Home目录所在硬盘的过程
  • 多重性校正:临床试验统计的关键防线
  • 文心大模型正式开源,开启AI普惠新时代
  • langchain从入门到精通(二十)——自定义文档加载器使用技巧及Blob 方案介绍
  • 佰力博科技与您探讨阻抗谱测量的基本原理和测量方法
  • web服务器搭建nginx
  • [特殊字符]【联邦学习实战】用 PyTorch 从 0 搭建一个最简单的联邦学习系统(含完整代码)
  • Python-Word文档、PPT、PDF以及Pillow处理图像详解
  • Objective-c把字符解析成字典
  • Python 数据分析与机器学习入门 (六):Seaborn 可视化技巧,图表更美观
  • 车间管理系统架构深度解析:高可用设计+工具技术选型指南