it编程 > App开发 > Android

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

11人参与 2025-07-04 Android

一、基础控件详解

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) // 背景色
)

核心参数说明

效果(示意图)

[浅灰色背景]
  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") // 按钮文字
}

核心参数说明

效果

[红色按钮] ♥ 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()
)

核心参数说明

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)
    }
)

核心参数说明

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)
)

参数说明

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

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")
    }
}

关键方法

布局效果

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

三、常见问题

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组件布局内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

在Android中实现根据手势的图片缩放功能

07-06

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

07-08

Jenkins分布式集群配置方式

07-08

zookeeper端口说明及介绍

07-08

Android ClassLoader加载机制详解

07-08

Android实现多进程数据共享的方法解析

06-22

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论