如何从两个小部件组成一个新的 UI 元素?

时间:2021-04-26 08:26:07

标签: android android-jetpack android-jetpack-compose

Image 我在 Android 中有一个普通的 Button 和一个星形图标。我想将它们组合成一个新的按钮图标,其中星形位于上角之一,如下所示:

enter image description here

当我使用 Row 时,两者是分开的。如您所见,星星应与按钮的一个角落重叠。我该怎么做?

编辑:感谢我使用的 Gabriele Mariotti

Box {

    Button(
        id = "btnButton",
        modifier = Modifier
            .padding(end = 48)
        onClick = {
            //..
        }
    )

    IconWithStar(
        modifier = Modifier
            .scale(0.65f)
    )
}

左上角绑定了星星图标,我该如何修改?

1 个答案:

答案 0 :(得分:2)

您可以用 Box 包裹组合物并使用 align/offset 修饰符来调整它们的位置。

Box(Modifier.padding(top=40.dp)){
    Button(
        onClick = {}) 
    {
        Text("Hello World")
    }
    Icon(
        Icons.Filled.Star, "",
        modifier =Modifier
            .align(TopEnd)
            .offset(12.dp,-12.dp),
        tint = Yellow600
    )
}

enter image description here

要获得更多控制,您可以构建自定义 Layout
类似的东西:

Layout( content = {

        Button(
            modifier = Modifier.layoutId("button"),
            onClick = { /* ... */ })
        {
            Text("Hello World")
        }
        Icon(Icons.Filled.Star, "",
            Modifier.layoutId("icon"),
            tint = Yellow600)
}){ measurables, incomingConstraints ->

    val constraints = incomingConstraints.copy(minWidth = 0, minHeight = 0)
    val buttonPlaceable =
        measurables.find { it.layoutId == "button" }?.measure(constraints)
    val iconPlaceable =
        measurables.find { it.layoutId == "icon" }?.measure(constraints)

    //align the icon on the top/end edge
    layout(width = widthOrZero(buttonPlaceable) + widthOrZero(iconPlaceable)/2,
        height = heightOrZero(buttonPlaceable)+ heightOrZero(iconPlaceable)/2){

        buttonPlaceable?.placeRelative(0, heightOrZero(iconPlaceable)/2)
        iconPlaceable?.placeRelative(widthOrZero(buttonPlaceable)- widthOrZero(iconPlaceable)/2,
           0)

    }
}


internal fun widthOrZero(placeable: Placeable?) = placeable?.width ?: 0
internal fun heightOrZero(placeable: Placeable?) = placeable?.height ?: 0

enter image description here