我的目的是创建一个黑框水平移动的动画。为此,如果我按第二个按钮,我会增加偏移(x 坐标),如果我按第一个按钮,我会返回到初始状态。
@Composable
fun Screen() {
val offsetX = remember { Animatable(0f) }
val coroutineScope = rememberCoroutineScope()
Column(
Modifier.fillMaxSize().padding(start = 16.dp, end = 16.dp, bottom = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.height(40.dp)
.fillMaxWidth()
.clip(CircleShape)
.background(Color.White)
.padding(horizontal = 4.dp, vertical = 2.dp),
) {
Box(
modifier = Modifier
.size(100.dp, 40.dp)
.clip(CircleShape)
.offset(x = offsetX.value.dp)
.background(Color.Black, CircleShape)
)
Button(onClick = {
coroutineScope.launch {
offsetX.animateTo(0f, tween(400))
}
}) {
Text("reset")
}
Button(onClick = {
coroutineScope.launch {
offsetX.animateTo(80f, tween(400))
}
}) {
Text("80")
}
}
}
}
我尝试通过修改偏移量(x坐标)来创建移动盒子的动画。但是,当我增加偏移量时,起始侧会移动,但结束侧不会移动,因此它的效果是减小宽度,而不是移动,这正是我想要做的。
@Composable
fun Screen() {
val offsetX = remember { Animatable(0f) }
val coroutineScope = rememberCoroutineScope()
Column(
Modifier
.fillMaxSize()
.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center // Center the content vertically
) {
Box(
modifier = Modifier
.height(40.dp)
.fillMaxWidth()
.clip(CircleShape)
.background(Color.White)
.padding(horizontal = 4.dp, vertical = 2.dp),
) {
Box(
modifier = Modifier
.size(100.dp, 40.dp)
.clip(CircleShape)
.offset(x = offsetX.value.dp) // This will move the box horizontally
.background(Color.Black, CircleShape)
)
}
Spacer(modifier = Modifier.height(16.dp)) // Add some space between the box and buttons
Row(
horizontalArrangement = Arrangement.spacedBy(16.dp) // Spacing between buttons
) {
Button(onClick = {
coroutineScope.launch {
offsetX.animateTo(0f, tween(400))
}
}) {
Text("Reset")
}
Button(onClick = {
coroutineScope.launch {
offsetX.animateTo(80f, tween(400))
}
}) {
Text("80")
}
}
}
}
试试这个