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