当前位置: 代码网 > it编程>App开发>Android > Android中Compose常用组件及布局使用方法示例详解

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

2025年07月04日 Android 我要评论
一、基础控件详解1. text - 文本控件text( text = "hello compose", // 必填,显示文本 color = color.blue, // 文字颜

一、基础控件详解

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

(0)

相关文章:

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

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com