'Create vertical chain with respect to other element in jetpack compose ConstraintLayout?
Solution 1:[1]
There are two solutions. The first solution requires that the height of the content on the right of the circle is fixed, while in the second solution, it is not fixed but is bound by constraints:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity(intent)
setContent {
Column(modifier = Modifier.fillMaxSize()) {
// First solution
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
Box(
modifier = Modifier
.size(100.dp)
.background(color = Color.Red, shape = RoundedCornerShape(50.dp))
)
Column(
modifier = Modifier
.height(100.dp)
.padding(start = 20.dp), verticalArrangement = Arrangement.Center
) {
Text("Line 1 goes here")
Text("Line 2 goes here")
}
}
Spacer(modifier = Modifier
.requiredHeight(30.dp)
.fillMaxWidth())
// Second solution
ConstraintLayout(modifier = Modifier.fillMaxWidth()) {
val (left, right) = createRefs()
Box(modifier = Modifier
.size(100.dp)
.background(color = Color.Red, shape = RoundedCornerShape(50.dp))
.constrainAs(left) {
start.linkTo(parent.start)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
})
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier
.padding(start = 20.dp)
.constrainAs(right) {
start.linkTo(left.end)
top.linkTo(left.top)
end.linkTo(parent.end)
bottom.linkTo(left.bottom)
width = Dimension.fillToConstraints
height = Dimension.fillToConstraints
}) {
Text("Line 1 goes here")
Text("Line 2 goes here")
}
}
}
}
}
}
Solution 2:[2]
Like suggested inside the documentation of createVerticalChain()
, you can "Use constrain with the resulting VerticalChainReference to modify the top and bottom constraints of this chain.":
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (box, text1, text2) = createRefs()
val chainRef = createVerticalChain(text1, text2, chainStyle = ChainStyle.Packed)
constrain(chainRef) {
top.linkTo(box.top)
bottom.linkTo(box.bottom)
}
Box(modifier = Modifier
.size(100.dp)
.padding(16.dp)
.background(color = Color.Red, shape = RoundedCornerShape(50.dp))
.constrainAs(box) {
start.linkTo(parent.start)
top.linkTo(parent.top)
}
)
Text("Line 1 goes here",
modifier = Modifier
.constrainAs(text1) {
start.linkTo(box.end)
end.linkTo(parent.end)
top.linkTo(box.top)
bottom.linkTo(text2.top)
width = Dimension.fillToConstraints
}
)
Text("Line 2 goes here",
modifier = Modifier
.constrainAs(text2) {
start.linkTo(box.end)
end.linkTo(parent.end)
top.linkTo(text1.bottom)
bottom.linkTo(box.bottom)
width = Dimension.fillToConstraints
}
)
}
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 | Johann |
Solution 2 |