正如在 XML 中我们过去常常向文本视图添加可绘制对象一样,那么 compose Text 中 android:drawableLeft, android:drawableRight 的等价物是什么?。除了使用 row(){ Image() Text()}
之外,还有什么简单的方法可以实现这一点吗?答案 0 :(得分:0)
据我所知,直到 rc01
Compose 不提供此功能。
我能够使用 ConstraintLayout
获得类似的结果。
@Composable
fun DrawableWrapper(
modifier: Modifier = Modifier,
@DrawableRes drawableTop: Int? = null,
@DrawableRes drawableStart: Int? = null,
@DrawableRes drawableBottom: Int? = null,
@DrawableRes drawableEnd: Int? = null,
content: @Composable () -> Unit,
) {
ConstraintLayout(modifier) {
val (refImgStart, refImgTop, refImgBottom, refImgEnd, refContent) = createRefs()
Box(Modifier.constrainAs(refContent) {
top.linkTo(drawableTop?.let { refImgTop.bottom } ?: parent.top)
bottom.linkTo(drawableBottom?.let { refImgBottom.top } ?: parent.bottom)
start.linkTo(drawableStart?.let { refImgStart.end } ?: parent.start)
end.linkTo(drawableEnd?.let { refImgEnd.start } ?: parent.end)
}) {
content()
}
drawableTop?.let {
Image(
painter = painterResource(id = it),
contentDescription = null,
Modifier.constrainAs(refImgTop) {
top.linkTo(parent.top)
start.linkTo(refContent.start)
end.linkTo(refContent.end)
}
)
}
drawableStart?.let {
Image(
painter = painterResource(id = it),
contentDescription = null,
Modifier.constrainAs(refImgStart) {
top.linkTo(refContent.top)
bottom.linkTo(refContent.bottom)
start.linkTo(parent.start)
}
)
}
drawableBottom?.let {
Image(
painter = painterResource(id = it),
contentDescription = null,
Modifier.constrainAs(refImgBottom) {
bottom.linkTo(parent.bottom)
start.linkTo(refContent.start)
end.linkTo(refContent.end)
}
)
}
drawableEnd?.let {
Image(
painter = painterResource(id = it),
contentDescription = null,
Modifier.constrainAs(refImgEnd) {
top.linkTo(refContent.top)
bottom.linkTo(refContent.bottom)
end.linkTo(parent.end)
}
)
}
}
}
所以你可以这样使用:
DrawableWrapper(
drawableTop = R.drawable.ic_android_orange,
drawableStart = R.drawable.ic_android_orange,
drawableBottom = R.drawable.ic_android_orange,
drawableEnd = R.drawable.ic_android_orange,
) {
Text(text = "A long Text ALL")
}
结果如下: