MotionLayout可以管理应用中的运动轨迹和控件的动画。因为是ConstraintLayout的子类,所以很多属性是和ConstraintLayout一样的。这个动画相较于属性动画、逐帧动画有更丰富的功能,而且还可以进行拓展,并且可以和CoordinatorLayout进行配合使用。而且用法上会简单很多,有些动画效果完全可以使用MotionLayout而不用去自定义View。可以提高一部分的工作效率,这里记录下基本的使用方式,进行下简单的了解。其余的用法可以在文末查看官方文档
需要添加依赖
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
这里先创建一个布局,让里面的TextView做动画效果,注意其id
activity_montion.xml
<androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutDescription="@xml/scene_01"
tools:context=".MotionActivity">
<TextView
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="标题"
android:layout_marginTop="100dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
androidx.constraintlayout.motion.widget.MotionLayout>
创建res/xml/scene_01.xml,内容如下,注意其运动的id与上述布局运动的id保持一致
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:motion="http://schemas.android.com/apk/res-auto">
<Transition
motion:constraintSetStart="@+id/start"
motion:constraintSetEnd="@+id/end"
motion:duration="1000">
<OnSwipe
motion:touchAnchorId="@+id/button"
motion:touchAnchorSide="right"
motion:dragDirection="dragRight" />
Transition>
<ConstraintSet android:id="@+id/start">
<Constraint
android:id="@+id/button"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_marginStart="8dp"
motion:layout_constraintBottom_toBottomOf="parent"
motion:layout_constraintStart_toStartOf="parent"
motion:layout_constraintTop_toTopOf="parent" />
ConstraintSet>
<ConstraintSet android:id="@+id/end">
<Constraint
android:id="@+id/button"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_marginEnd="8dp"
motion:layout_constraintBottom_toBottomOf="parent"
motion:layout_constraintEnd_toEndOf="parent"
motion:layout_constraintTop_toTopOf="parent" />
ConstraintSet>
MotionScene>
以下来自官方文档
请注意以下几点:
包含运动的基本定义。
motion:constraintSetStart和motion:constraintSetEnd指的是运动的端点。这些端点在 MotionScene 后面的元素中定义。
motion:duration指定完成运动所需的毫秒数。
可让您通过轻触控制运动。
motion:touchAnchorId指的是您可以滑动并拖动的视图。
motion:touchAnchorSide表示我们从右侧拖动视图。
motion:dragDirection表示拖动的进度方向。例如,motion:dragDirection="dragRight"表示当您向右拖动时,进度会增加。
是定义描述您的运动的各种限制条件的位置。在此示例中,我们为运动的每个端点定义一个ConstraintSet。这些端点垂直居中(通过app:layout_constraintTop_toTopOf="parent"和app:layout_constraintBottom_toBottomOf="parent")。在水平方向上,端点位于屏幕最左侧和最右侧。
这里需要注意motion:touchAnchorId和Constraint中的android:id与布局中运动的控件的id保持一致
然后直接在Activity中加载布局,加载后,手势拖动控件会发现出现动画效果