Jetpack Compose 自定义布局以及固有特性测量

本文详细介绍了如何在Jetpack Compose中实现自定义布局,包括使用Modifier.layout和Layout创建自定义布局。同时,讨论了Intrinsic Measurement的重要性,它允许在测量子项时获取其最大最小尺寸,从而优化性能并避免多次测量的问题。文中通过实例展示了Intrinsic Measurement的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇文章我们会讲解下,Compose中如何去自定义布局,以及Intrinsic Measurement(官方翻译为固有特性测量)的理解跟使用。

一:自定义布局

自定义布局可以通过两种方式去处理,一种是使用布局修饰符Modifier.layout,一种是使用Layout去创建自定义布局。我们先来讲下Modifier.layout的方式

1.1 使用布局修饰符来实现自定义布局

我们自定义一个Modifier的扩展函数,Modifier.customCornerPosLayout。该方法的作用就是可以按我们传入的CornerPosition,去把view放置在左上角,左下角,右上角,右下角。代码如下:

enum class CornerPosition{
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight
}

fun Modifier.customCornerPosLayout(pos:CornerPosition) = layout { measurable, constraints ->
    // Measure the composable
    val placeable = measurable.measure(constraints)
    layout(constraints.maxWidth, constraints.maxHeight) {
        // Where the composable gets placed
        when(pos){
            CornerPosition.TopLeft->{
                placeable.placeRelative(0, 0)
            }
            CornerPosition.TopRight->{
                placeable.placeRelative(constraints.maxWidth-placeable.width, 0)
            }
            CornerPosition.BottomLeft->{
                placeable.placeRelative(0, constraints.maxHeight-placeable.height)
            }
            CornerPosition.BottomRight->{
                placeable.placeRelative(constraints.maxWidth-placeable.width, constraints.maxHeight-placeable.height)
            }
        }
    }
}
复制代码
  • 首先我们声明一个枚举。叫CornerPosition,枚举有四种取值,TopLeft表示左上角,TopRight右上角,BottomLeft左下角,BottomRight又下角。
  • 接着我们定义一个Modifier的扩展函数customCornerPosLayout,入参是pos:CornerPosition我们的枚举类
  • customCornerPosLayout的实现是通过layout的lamda去实现。其实是调用Modifier.layout去实现自定义布局。有两个参数一个是measurable,一个是constraints父控件的约束
  • 自定义布局第一步val placeable = measurable.measure(constraints) 是根据measurable跟constraints父控件的约束,通过方法measurable.measure(constraints)去生成一个placeable类。该类拥有子控件的宽width跟高height
  • 自定义布局的第二部 需要调用layout(w,h)的方法去设置当前view能使用的宽高。我们这里是用layout(constraints.maxWidth, constraints.maxHeight) 传入的是constraints.max
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值