android - 如何从两个小部件组成一个新的 UI 元素?
问题描述
图片 我在 Android 中有一个普通的按钮和一个星形图标。我想将它们组合成一个新的 Button 图标,其中星形位于上角之一,如下所示:
当我使用时Row
,两者是分开的。如您所见,星形应与按钮的一个角重叠。我怎样才能做到这一点?
编辑:感谢我使用的 Gabriele Mariotti
Box {
Button(
id = "btnButton",
modifier = Modifier
.padding(end = 48)
onClick = {
//..
}
)
IconWithStar(
modifier = Modifier
.scale(0.65f)
)
}
星形图标绑定在左上角,我该如何修改?
解决方案
您可以用 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
推荐阅读
- excel - 导出第 1 行中带有引号分隔符的文本文件的过程 - Excel
- c# - 如何在 swashbuckl asp.net core web api 上添加自定义标头
- jquery - 如何申请和取消折扣
- php - MySQL JSON 数据类型更新与删除
- api - APIGEE 修订比较
- angular - 如何在 Angular 组件 + webpack 中预处理并正确包含 scss
- jenkins - CI/CD 管道中的工作流程 - Jenkins、Kubernetes 和 SVN/GitHub 代码库
- android - 动画 GIF 无法播放
- ruby-on-rails - 没有使用 react-rails prerender 渲染 Material-UI 组件
- delphi - Delphi 字符串 + #32 控制字符