Reputation: 13
I am trying to use Compose's ConstraintLayout
composable to place a composable on 30% midway through the screen from the top.
I tried using the pivotY
attribute in the constraint DSL to no avail, translateY
worked but I don't want to specify Dp for obvious reasons)
Here is a test composable I've tested with
@Composable
@Preview
fun Test() {
ConstraintLayout(
modifier = Modifier.fillMaxWidth().aspectRatio(1f)
) {
val btn = createRef()
Box(
modifier = Modifier
.size(64.dp)
.background(Color.Red)
.constrainAs(btn) {
bottom.linkTo(parent.bottom)
top.linkTo(parent.top)
pivotY = 30f // or -30f, none is working (same thing with 0.3f of -0.3f)
}
)
}
}
Upvotes: 0
Views: 45
Reputation: 116
To place a composable at 30% from the top of the screen using Jetpack Compose's ConstraintLayout, you can use the FractionalPosition modifier to achieve this. The pivotY attribute in the constraint DSL is not the right approach for this task. Instead, you can position the element by specifying the fraction of the parent's height. here is the example
@Composable
@Preview
fun Test() {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
) {
val btn = createRef()
Box(
modifier = Modifier
.size(64.dp)
.background(Color.Red)
.constrainAs(btn) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}
.offset(y = (-0.35f * it.maxHeight).toDp()) // Positioning the box at 30% from the top
)
}
}
fun Float.toDp(): Dp = (this / Resources.getSystem().displayMetrics.density).dp
Upvotes: 0
Reputation: 13
I've found the answer in here.
found out i have to use another linkTo
function
@Composable
@Preview
fun Test() {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f),
) {
val btn = createRef()
Box(
modifier = Modifier
.size(64.dp)
.background(Color.Red)
.constrainAs(btn) {
linkTo(parent.top, parent.bottom, bias = 0.3f)
},
)
}
}
Upvotes: 0