android动画顶起布局,动画布局:MotionLayout用法解析,让你的布局运动起来!

介绍

动画布局MotionLayout是ConstraintLayout的子类,它具有ConstraintLayout的所有属性。同时MotionLayout支持在XML中完全描述一个复杂的动画,而不需要通过Java代码来实现。(有没有很开心!)

话不多说,先看运行效果,再看代码学习起来!

效果预览

0c3ee122951f

控件解析

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" />

大功告成!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值