'How to add drawable to a Text in Compose?
As in XML we used to add a drawable to a TextView
, so What is the equivalent of android:drawableLeft
, android:drawableRight
in Jetpack Compose Text
? Is there any easy way to achieve this other than using Row { Image() Text() }
?
Solution 1:[1]
As far as I know, until rc01
Compose does not provide this feature.
I was able to achieve a similar result using 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)
}
)
}
}
}
So you can use this way:
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")
}
Here is the result:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | nglauber |