Adrian Grygutis
Adrian Grygutis

Reputation: 479

Get and set position of element programmatically in Jetpack Compose

Is it possible to get and set position/bounds programmatically of element on window? Let's say, we have simple Text and want to move it 50dp on y axis.

Text(text = "Hello", modifier = Modifier.padding(8.dp).fillMaxWidth())

Upvotes: 5

Views: 12089

Answers (2)

WernerD
WernerD

Reputation: 108

If I interpret your question correctly, then you would like to move a Text 50dp on the y-axis and the Text and the 50dp space above the text should be clickable.

This is one solution to create a small custom composable:

@Composable
fun TextWithPos(content: String, modifier: Modifier, x: Int, y: Int, clickFun: () -> Unit = {}) {

    Text(text = content, modifier = modifier
            .defaultMinSizeConstraints(minHeight = y.dp)
            .clickable(onClick = clickFun)
            .padding(top = y.dp))

}

This Composable sets up a Text with a minHeigth of some dp (minWidth not used here), then sets the clickable, then a padding with some dp. Actually, compose does no distinguish between margin and padding anymore, it's just some space.

Compose processes Modifiers in order, thus clickable covers the space (padding) and the text inside Text. If you move clickable below the padding then the clickable area only covers the text inside Text.

Here a Preview with a clickable action to show the clickable area. Because the function sets a modifier and hands it over to the custom composable these modifiers take precedence over the Modifier set in the custom composable.

@Preview(showBackground = true)
@Composable
fun TextPosPreview() {
    PlaygroundTheme {
        Column() {
            TextWithPos(content = "Hello", modifier = Modifier
                    .padding(start = 16.dp, end=16.dp), x = 0, y = 50) {
                counter++
            }

            var counter by remember { mutableStateOf(1) }
            Text(text = counter.toString(), modifier = Modifier
                    .padding(16.dp))

        }
    }
}

Upvotes: 5

Denys Nykyforov
Denys Nykyforov

Reputation: 86

https://developer.android.com/reference/kotlin/androidx/ui/layout/package-summary#offset

Text(text = "Hello", modifier = Modifier.padding(8.dp).offset(y = 50.dp))

Upvotes: 7

Related Questions