MotionLayout
要在 ConstraintLayout 中实现平滑的动画移动,你可以使用 MotionLayout,它是 ConstraintLayout 的一个子类,专门用于处理视图的平滑动画过渡。通过 MotionLayout,你可以通过修改约束、添加动画和设置目标位置来实现平滑过渡。
步骤:
1. 使用 MotionLayout 作为根布局。
2. 创建 motion_scene 文件来定义动画。
3. 在 MotionLayout 中设置目标约束。
4. 触发动画。
示例代码:
1. 创建 MotionLayout 作为根布局
首先,确保根布局是 MotionLayout,而不是传统的 ConstraintLayout。
<com.google.android.material.motionlayout.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/motionLayout" android:layout_width="match_parent" android:layout_height="match_parent" app:layoutDescription="@xml/motion_scene"> <TextView android:id="@+id/viewToMove" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World" android:textSize="24sp" /> </com.google.android.material.motionlayout.MotionLayout>
2. 创建 motion_scene.xml 文件
motion_scene.xml 定义了 MotionLayout 中的动画。你可以创建这个文件并将它放在 res/xml/ 目录下。
<?xml version="1.0" encoding="utf-8"?> <MotionScene xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <Transition app:constraintSetStart="@id/start" app:constraintSetEnd="@id/end" app:duration="1000"> <OnClick app:targetId="@id/viewToMove" app:clickAction="rotate"/> </Transition> <ConstraintSet android:id="@+id/start"> <Constraint android:id="@id/viewToMove" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" /> </ConstraintSet> <ConstraintSet android:id="@+id/end"> <Constraint android:id="@id/viewToMove" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent"/> </ConstraintSet> </MotionScene>
3. 触发动画
在你的 Activity 或 Fragment 中触发动画。
val motionLayout = findViewById<MotionLayout>(R.id.motionLayout) motionLayout.transitionToEnd() // 这会将视图移动到定义的终点
解释:
• MotionLayout 通过定义 motion_scene.xml 文件来描述从 start 约束集到 end 约束集的平滑过渡动画。
• app:duration=”1000″ 设置动画持续时间为 1000 毫秒(即 1 秒)。
• 使用 transitionToEnd() 方法,你可以在代码中启动动画,平滑地将视图移动到目标位置。
其他动画:
如果你想要在点击或其他操作时触发动画,可以通过 OnClick 事件来设置目标视图。
<OnClick app:targetId="@id/viewToMove" app:clickAction="rotate"/>
这里你可以设置更多的动画类型,如旋转、平移、缩放等。