最新版的constraintlayout-compose(写作时为1.0.0-beta02
)已经支持在Compose中使用MotionLayout
的部分特性。
按照文档的说明,您可以通过以下方式将其添加到项目中:
dependencies {
implementation("androidx.constraintlayout:constraintlayout-compose:1.0.0-beta02")
}
文档还提供了一个简单的示例,演示如何在两个约束集之间进行过渡:
@Preview(group = "motion8")
@Composable
public fun AttributesRotationXY() {
var animateToEnd by remember { mutableStateOf(false) }
val progress by animateFloatAsState(
targetValue = if (animateToEnd) 1f else 0f,
animationSpec = tween(6000)
)
Column {
MotionLayout(
modifier = Modifier
.fillMaxWidth()
.height(400.dp)
.background(Color.White),
motionScene = MotionScene("""{
ConstraintSets: { // all ConstraintSets
start: { // constraint set id = "start"
a: { // Constraint for widget id='a'
width: 40,
height: 40,
start: ['parent', 'start', 16],
bottom: ['parent', 'bottom', 16]
}
},
end: { // constraint set id = "start"
a: {
width: 40,
height: 40,
//rotationZ: 390,
end: ['parent', 'end', 16],
top: ['parent', 'top', 16]
}
}
},
Transitions: { // All Transitions in here
default: { // transition named 'default'
from: 'start', // go from Transition "start"
to: 'end', // go to Transition "end"
pathMotionArc: 'startHorizontal', // move in arc
KeyFrames: { // All keyframes go here
KeyAttributes: [ // keyAttributes key frames go here
{
target: ['a'], // This keyAttributes group target id "a"
frames: [25,50,75], // 3 points on progress 25% , 50% and 75%
rotationX: [0, 45, 60], // the rotationX angles are a spline from 0,0,45,60,0
rotationY: [60, 45, 0], // the rotationX angles are a spline from 0,60,45,0,0
}
]
}
}
}
}"""),
debug = EnumSet.of(MotionLayoutDebugFlags.SHOW_ALL),
progress = progress) {
Box(modifier = Modifier
.layoutId("a")
.background(Color.Red))
}
Button(onClick = { animateToEnd = !animateToEnd }) {
Text(text = "Run")
}
}
}
您可以在
这个维基页面和
约束布局存储库中阅读更多信息并跟踪进展。