最近在研究ConstraintLayout,顺便发现了它的子类MotionLayout。发现打开的动画世界的新大门。
效果图
github地址
使用方法 - PartOne
-
build.gradle中引用MotionLayout库
implementation 'com.android.support.constraint:constraint-layout:2.0.0-beta2'必须要是2.0以上的版本,2.0以上的版本才支持MotionLayout -
创建 MotionScene 文件并使用 app:layoutDescription 关联。在
<androidx.constraintlayout.motion.widget.MotionLayout>标签中添加app:layoutDescription="@xml/sample"
对MotionScene 文件进行分析
MotionScene节点
<?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:constraintSetEnd="@id/end"
app:constraintSetStart="@id/start">
</Transition>
<ConstraintSet android:id="@+id/start">
</ConstraintSet>
<ConstraintSet android:id="@+id/end">
</ConstraintSet>
</MotionScene>
Transition标签指定开始,结束的ConstrainSet。 ConstrainSet表示对应的场景,开始时的布局和结束时的布局
ConstraintSet结点
<Constraint id="">
<Motion/>
<Layout/>
<Transform/>
<CustomAttribute/>
<PropertySet/>
</Constraint>
Motion运动模型。弧线路径,时间模型等。每个控件可以单独设置时间模型 Layout 布局相关 Transform 动画变化。旋转、位移、缩放等属性。整个 Transition 也可以设置插值器 CustomAttribute 自定义属性
attributeName会加上set\get反射找到真正的函数名,比如backgroundColor就会调用setBackgroundColor()函数- custom(xxx)Value对应属性的数据类型
PropertySet 特定的属性
visibility、alpha等属性
Transition节点
<Transition app:constraintSetStart="@+id/start" app:constraintSetEnd="@+id/end" app:duration="1000">
<OnSwipe />
<OnClick />
<KeyPositionSet >
<KeyAttribute>
<CustomAttribute/>
</KeyAttribute>
<KeyPostion/>
<KeyCycle/>
<KeyTimeCycle/>
</KeyPositionSet>
</Transition>
OnSwipe标签
<OnSwipe app:touchAnchorId="@id/view"
app:dragDirection="dragDown"/>
<OnSwipe>在<Transtion>节点中支持参数:
touchAnchorId指的是哪一个控件响应触摸事件autoComolete默认是true,会根据动画完成的百分比自动到一个最近的一个状态dragDirection拖拽的方向
OnClick标签
<OnClick app:clickAction="toggle"
app:targetId="@id/toggle"/>
<OnClick>在<Transtion>节点中支持参数:clickAction
toggle反转状态transitionToEnd\Start通过动画到结束/起始状态jumpToEnd/Start没有动画直接到结束/起始状态
剩下的标签接下来在写。先根据上面的标签写个简单的Demo
Demo
初始状态
结束状态
代码分析(图片)
使用方法 - PartTwo
接着上面的Transition节点
KeyPositionSet标签
app:motionTarget目标对象的idapp:framePosition动画完成的百分比(0-100)
KeyAttribute属性关系字
<KeyAttribute
app:framePosition="0"
app:motionTarget="@id/image_film_cover"
android:alpha="0">
<CustomAttribute
app:attributeName="BackgroundColor"
app:customColorValue="@color/colorAccent"/>
</KeyAttribute>
可以设置位移,旋转,缩放等属性,同时还可以通过CustomAttribute添加自定义属性
KeyPosition 位置关键帧
percentX/Y 在关键帧时,对应路径的对应百分比
percentWidth/Height 在关键帧时,控件大小改变的百分比
curveFit 运动路径的样式(直线,曲线等)
keyPositionType 坐标系
- parentRelative (0,0)为父容器左上角
(1,1)为父容器右下角
- deltaRelative (0,0)为起始控件中心
(1,1)为结束控件中心
- pathRelative (0,0)为起始控件中心
(1,0)为结束控件中心