Android中Compose常用组件及布局使用方法示例详解

 更新时间:2025年07月04日 10:34:05   作者:xzkyd outpaper  
本文详解Android Compose常用组件(Text、Button、TextField、Image、ProgressIndicator)及布局(Column、Row、Box),涵盖核心参数、效果与实现方法,感兴趣的朋友跟随小编一起看看吧

一、基础控件详解

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.current
Button(
    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.current
    val screenWidth = configuration.screenWidthDp.dp
    if (screenWidth < 600.dp) {
        VerticalLayout() // 小屏:垂直布局
    } else {
        HorizontalLayout() // 大屏:水平布局
    }
}

到此这篇关于Android中Compose常用组件以及布局使用方法的文章就介绍到这了,更多相关android compose组件布局内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Android RecyclerView实现九宫格效果

    Android RecyclerView实现九宫格效果

    这篇文章主要为大家详细介绍了Android RecyclerView实现九宫格效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-06-06
  • Android开发入门之Appwidget用法分析

    Android开发入门之Appwidget用法分析

    这篇文章主要介绍了Android开发入门之Appwidget用法,较为详细的分析了App Widget的概念、功能、创建、使用方法与相关注意事项,需要的朋友可以参考下
    2016-07-07
  • Android应用中使用SharedPreferences类存储数据的方法

    Android应用中使用SharedPreferences类存储数据的方法

    这篇文章主要介绍了Android应用中使用SharedPreferences类存储数据的方法,SharedPreferences使用键值对应的方式进行存储,使用于少量的数据保存,需要的朋友可以参考下
    2016-04-04
  • Android实现简单卡片布局

    Android实现简单卡片布局

    这篇文章主要为大家详细介绍了Android实现卡片布局的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-10-10
  • 利用Flutter轻松制作红包界面

    利用Flutter轻松制作红包界面

    这篇文章主要为大家详细介绍了如何利用Flutter实现轻松制作一个红包界面,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以了解一下
    2022-11-11
  • Android在OnCreate中获取控件的宽度和高度的实现代码

    Android在OnCreate中获取控件的宽度和高度的实现代码

    在Android中,有时需要对控件进行测量,得到的控件宽度和高度可以用来做一些计算。在需要自适应屏幕的情况下,这种计算就显得特别重要
    2012-11-11
  • Android利用绘制缓冲实现代码雨效果

    Android利用绘制缓冲实现代码雨效果

    看过很多代码雨的前端实现,却很少看到过Android代码雨效果的实现,当然 open gl es的实现是有的,一个主要的原因是,在Android Canvas绘制时,很少有人考虑使用绘制缓冲,所以本文将给大家介绍Android如何利用绘制缓冲实现代码雨效果,需要的朋友可以参考下
    2024-03-03
  • Android使用控件ImageView加载图片的方法

    Android使用控件ImageView加载图片的方法

    这篇文章主要为大家详细介绍了Android使用ImageView加载图片的方法,Android ImageView如何加载网络图片资源,感兴趣的小伙伴们可以参考一下
    2016-05-05
  • android自定义窗口标题示例分享

    android自定义窗口标题示例分享

    这篇文章主要介绍了android自定义窗口标题示例,需要的朋友可以参考下
    2014-03-03
  • Android中应用多进程的整理总结

    Android中应用多进程的整理总结

    Android平台支持多进程通信,也支持应用内实现多进程,下面这篇文章主要给大家介绍了关于Android中应用多进程的相关资料,文中介绍的很详细,相信对大家具有一定的参考借鉴价值,有需要的朋友们下面来一起看看吧。
    2017-01-01

最新评论