首页 > 解决方案 > 如何从两个小部件组成一个新的 UI 元素?

问题描述

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

在此处输入图像描述

当我使用时Row,两者是分开的。如您所见,星形应与按钮的一个角重叠。我怎样才能做到这一点?

编辑:感谢我使用的 Gabriele Mariotti

Box {

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

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

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

标签: androidandroid-jetpackandroid-jetpack-compose

解决方案


您可以用 a 包裹可组合项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
    )
}

在此处输入图像描述

要获得更多控制权,您可以构建自定义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

在此处输入图像描述


推荐阅读