Home > Software design >  How to make middle view sit in bound of between two images? (JetpackCompose)
How to make middle view sit in bound of between two images? (JetpackCompose)

Time:08-30

I have such a view

@Composable
fun LongText() {
    ConstraintLayout(

    ) {
        val (leftImg, headerTitle, rightImg) = createRefs()

        Image(
            modifier = Modifier
                .constrainAs(leftImg) {
                    top.linkTo(parent.top)
                    start.linkTo(parent.start)
                    bottom.linkTo(parent.bottom)
                },
            painter = painterResource(id = R.drawable.ic_launcher_foreground),
            contentDescription = ""
        )

        Text(
            text = "LONGTEXTLONGTEXTLONGTEXTLONGTEXTLONGTEXT",
            textAlign = TextAlign.Left,
            modifier = Modifier
                .padding(start = 8.dp)
                .constrainAs(headerTitle) {
                    start.linkTo(leftImg.end)
                    top.linkTo(parent.top)
                    end.linkTo(rightImg.start)
                    bottom.linkTo(parent.bottom)
                },
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            color = Color.Red
        )

        Image(
            modifier = Modifier
                .constrainAs(rightImg) {
                    top.linkTo(parent.top)
                    end.linkTo(parent.end)
                    bottom.linkTo(parent.bottom)
                },
            painter = painterResource(id = R.drawable.ic_launcher_foreground),
            contentDescription = ""
        )
    }
}

There are two problems that I am trying to find out:

  1. Why maxLines & overflow doesn't work for Text view? I expect that verylong text will be collapsed with three dots once it reaches the image on the right, what is the problem here?
maxLines = 1,
overflow = TextOverflow.Ellipsis

Result:

enter image description here

  1. Why align doesn't work for short text? I mean according to this line textAlign = TextAlign.Left I expect that short text appear on the left, close to the left image, however instead I have this text in the middle

Result:

enter image description here

CodePudding user response:

You can use a simple Row applying a weight(1f) modifier to the Text

    Row(Modifier.fillMaxWidth()) {
        Image(
            painter = painterResource(id = R.drawable.xxx),
            contentDescription = ""
        )

        Text(
            text = "LONGTEXTLONGTEXTLONGTEXTLONGTEXTLONGTEXT",
            textAlign = TextAlign.Left,
            modifier = Modifier
                .padding(start = 8.dp).weight(1f),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            color = Color.Red
        )

        Image(
            painter = painterResource(id = R.drawable.ic_xxx),
            contentDescription = ""
        )
    }

enter image description here

  • Related