Last active
May 28, 2024 15:10
-
-
Save randroid88/2678c8e20c4211cd5a4bbacf70f25274 to your computer and use it in GitHub Desktop.
Barrier example showing how to use it to align composables in a ConstraintLayout for Android.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.compose.foundation.background | |
import androidx.compose.foundation.layout.* | |
import androidx.compose.material3.Button | |
import androidx.compose.material3.Text | |
import androidx.compose.runtime.Composable | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.graphics.Color | |
import androidx.compose.ui.layout.layoutId | |
import androidx.compose.ui.unit.dp | |
import androidx.constraintlayout.compose.ConstraintLayout | |
import androidx.constraintlayout.compose.ConstraintSet | |
@Composable | |
fun Playground() { | |
ConstraintLayout( | |
constraintSet = ConstraintSet { | |
val button1 = createRefFor("button1") | |
val button2 = createRefFor("button2") | |
val text = createRefFor("text") | |
// Create a top barrier based on button1 and button2 | |
val bottomBarrier = createBottomBarrier(button1, button2) | |
constrain(button1) { | |
top.linkTo(parent.top, margin = 50.dp) | |
start.linkTo(parent.start, margin = 16.dp) | |
} | |
constrain(button2) { | |
top.linkTo(parent.top, margin = 100.dp) | |
start.linkTo(button1.end, margin = 16.dp) | |
} | |
constrain(text) { | |
top.linkTo(bottomBarrier) // Align the top of the text to the top barrier | |
start.linkTo(parent.start, margin = 16.dp) | |
} | |
}, | |
modifier = Modifier.fillMaxSize() | |
) { | |
Button(onClick = {}, modifier = Modifier.layoutId("button1")) { | |
Text("Button 1") | |
} | |
Button(onClick = {}, modifier = Modifier.layoutId("button2")) { | |
Text("Button 2") | |
} | |
Text( | |
text = "This text is aligned with the top barrier", | |
modifier = Modifier.layoutId("text").background(Color.LightGray) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment