MotionLayout 基础
首先,我们需要从 MotionLayout
的一些基本属性和用法讲起,这样对于我们后面的实际操作将会很有帮助。
引入 MotionLayout 库
1dependencies {
2 implementation ‘com.android.support.constraint:constraint-layout:2.0.0-beta2’
3}
4复制代码
目前,MotionLayout
仍处于 beta
版本,虽然官方之前说过 MotionLayout
的动画辅助工具将会在 beta``ConstraintLayout
在布局文件中使用 MotionLayout
想要使用 MotionLayout
,只需要在布局文件中作如下声明即可:
1<android.support.constraint.motion.MotionLayout
2 xmlns:android=“http://schemas.android.com/apk/res/android”
3 xmlns:tools=“http://schemas.android.com/tools”
4 xmlns:app=“http://schemas.android.com/apk/res-auto”
5 android:layout_width=“match_parent”
6 android:layout_height=“match_parent”
7 app:layoutDescription="@xml/scene1">
8
9</android.support.constraint.motion.MotionLayout>
10复制代码
由于 MotionLayout
作为 ConstraintLayout
的子类,那么就自然而然地可以像 ConstraintLayout``Motio![](https://www.hualigs.cn/image/61dba891ed8ee.jpg) nLayout
的用处可远不止这些。我们先来看看 MotionLayout 的构成:
由上图可知,MotionLayout 可分为 <View>
和 <Helper>
两个部分。 <View>
部分可简单理解为一个ConstraintLayout
,至于 <Helper>
其实就是我们的“动画层”了。MotionLayout 为我们提供了layoutDescription
属性,我们需要为它传入一个 MotionScene
包裹的 XML
MotionScene:传说中的“百宝袋”
什么是 MotionScene?结合上图 MotionScene 主要由三部分组成: StateSet
、ConstraintSet
和 Transition
。为了让大家快速理解和使用 MotionScene,本文将重点讲解ConstarintSet
和 Transition
,至于 StateSet
首先,我们从实现下面这个简单的效果讲起:
GIF 画质有点渣,见谅,但从上图我们可以发现这是一个简单的平移动画,通过点击自身(篮球)来触发,让我们来通过 MotionLayout
1<?xml version=“1.0” encoding=“utf-8”?>
2<android.support.constraint.motion.MotionLayout
3 xmlns:android=“http://schemas.android.com/apk/res/android”
4 xmlns:tools=“http://schemas.android.com/tools”
5 xmlns:app=“http://schemas.android.com/apk/res-auto”
6 android:layout_width=“match_parent”
7 android:layout_height=“match_parent”
8 app:layoutDescription=