介绍
动画布局MotionLayout是ConstraintLayout的子类,它具有ConstraintLayout的所有属性。同时MotionLayout支持在XML中完全描述一个复杂的动画,而不需要通过Java代码来实现。(有没有很开心!)
话不多说,先看运行效果,再看代码学习起来!
效果预览
控件解析
MotionLayout用来处理两个ConstraintSet之间的切换,并在根据两个ConstraintSet的CustomAttribute参数来自动生成切换动画,MotionLayout会管理你的触摸事件通过跟踪手指的速度,并将其与系统中的视图速度相匹配。从而可以自然地在两者之间通过触摸滑动平稳过渡。并且在动画里面加入了关键帧的概念,使得其自动生成动画在运行时某一阶段会运行到关键帧的状态。
与通常的布局不同,MotionLayout所做的约束保存在一个单独的XML文件MotionScene中,该文件存储在您的res/xml目录中。
MotionScene文件可以包含指定动画所需的全部内容,例如前面提到的ConstraintSets、ConstraintSets直接的过渡、关键帧、触摸处理等等。
控件通过 app:layoutDescription="@xml/activity_case45_scene"属性关联MotionScene布局文件。完成动画的切换效果定义。
控件通过 app:showPaths="true"属性展示滑动的轨迹。
用法
第一步:添加MD依赖(app下build.gradle中)
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation "com.google.android.material:material:1.1.0-alpha07"
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
第二步:布局文件
改变根布局ConstraintLayout—>MotionLayout
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/activity_case45_scene"
app:showPaths="true"
tools:context=".blog.Case45">
android:id="@+id/rect"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="@color/blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent" />
第三步:MotionScene布局文件
xmlns:app="http://schemas.android.com/apk/res-auto">
android:id="@+id/rect"
android:layout_width="70dp"
android:layout_height="70dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
/>
android:id="@+id/rect"
android:layout_width="70dp"
android:layout_height="70dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
app:constraintSetStart="@+id/start"
app:constraintSetEnd="@id/end"
app:duration="1000">
app:clickAction="toggle"
app:targetId="@+id/rect" />
大功告成!