介紹
??動畫布局MotionLayout是ConstraintLayout的子類,它具有ConstraintLayout的所有屬性。同時MotionLayout支持在XML中完全描述一個復雜的動畫,而不需要通過Java代碼來實現(xiàn)。(有沒有很開心!)
??話不多說,先看運行效果,再看代碼學習起來!
效果預覽

控件解析
- MotionLayout用來處理兩個ConstraintSet之間的切換,并在根據(jù)兩個ConstraintSet的CustomAttribute參數(shù)來自動生成切換動畫,MotionLayout會管理你的觸摸事件通過跟蹤手指的速度,并將其與系統(tǒng)中的視圖速度相匹配。從而可以自然地在兩者之間通過觸摸滑動平穩(wěn)過渡。并且在動畫里面加入了關(guān)鍵幀的概念,使得其自動生成動畫在運行時某一階段會運行到關(guān)鍵幀的狀態(tài)。
- 與通常的布局不同,MotionLayout所做的約束保存在一個單獨的XML文件MotionScene中,該文件存儲在您的res/xml目錄中。
- MotionScene文件可以包含指定動畫所需的全部內(nèi)容,例如前面提到的ConstraintSets、ConstraintSets直接的過渡、關(guān)鍵幀、觸摸處理等等。
- 控件通過 app:layoutDescription="@xml/activity_case45_scene"屬性關(guān)聯(lián)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
<?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/activity_case45_scene"
app:showPaths="true"
tools:context=".blog.Case45">
<View
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" />
</androidx.constraintlayout.motion.widget.MotionLayout>
第三步: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">
<ConstraintSet android:id="@+id/start">
<!--自定義動畫開始狀態(tài)-->
<Constraint
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" />
/>
</ConstraintSet>
<ConstraintSet android:id="@+id/end">
<!--自定義動畫結(jié)束狀態(tài)-->
<Constraint
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" />
</ConstraintSet>
<Transition
<!--轉(zhuǎn)換狀態(tài)+定義延遲-->
app:constraintSetStart="@+id/start"
app:constraintSetEnd="@id/end"
app:duration="1000">
<OnClick
app:clickAction="toggle"
app:targetId="@+id/rect" />
<KeyFrameSet></KeyFrameSet>
</Transition>
</MotionScene>