ConstraintLayout2.0一篇寫不完之MotionEffect

點擊上方藍字關注我,知識會給你力量

MotionEffect
MotionEffect是2.1中的一個新的MotionHelper,可以讓你根據視圖的整體運動方向,自動為其引用的視圖添加關鍵幀。它可以簡化很多過渡動畫的創(chuàng)作。
為了更好地理解它的作用,請看下面的例子。這個例子只使用了MotionLayout的start和end功能,它自動創(chuàng)建了兩種場景下的過渡效果。

默認的兩種狀態(tài)之間的過渡做了一個線性插值的移動效果——這個展示結果是混亂的,并不令人愉快。
如果我們看這個例子,我們可以識別出只向西移動的元素(2、3、6、9),而其他元素則以其它不同的模式移動(1、4、5、7、8)。

我們可以使用MotionEffect對這些元素應用淡入淡出的效果,給人帶來更愉悅的效果。

可以查看下面的demo。
<androidx.constraintlayout.motion.widget.MotionLayout ... >
<TextView android:id="@+id/t1" ... />
<TextView android:id="@+id/t2" ... />
<TextView android:id="@+id/t3" ... />
<TextView android:id="@+id/t4" ... />
<TextView android:id="@+id/t5" ... />
<TextView android:id="@+id/t6" ... />
<TextView android:id="@+id/t7" ... />
<TextView android:id="@+id/t8" ... />
<TextView android:id="@+id/t9" ... />
...
<androidx.constraintlayout.helper.widget.MotionEffect
android:id="@+id/fade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:constraint_referenced_ids="t1,t2,t3,t4,t5,t6,t7,t8,t9"
/>
</androidx.constraintlayout.motion.widget.MotionLayout>
Controling which views get the effect
首先,只有MotionEffect中引用的視圖才有可能得到效果。
其次,默認情況下,我們會自動計算這些視圖的主要移動方向(在北、南、東、西之間),只有與該方向相反移動的視圖才會得到應用于它們的效果。
使用motionEffect_move=auto|north|south|east|west,你可以覆蓋它來指定你想要效果應用到哪個方向。
你也可以使用motionEffect_strict=true|false來讓這個效果嚴格地應用于(或不應用于)做這個運動的元素。
默認效果 默認情況下,效果將應用淡出/淡入;你可以通過以下屬性控制alpha的數量以及效果的開始/結束。
app:motionEffect_start="keyframe"
app:motionEffect_end="keyframe"

你也可以控制alpha和translation的數值。
app:motionEffect_alpha="alpha"
app:motionEffect_translationX="dimension"
app:motionEffect_translationX="dimension"
Custom effect
你也可以引用一個ViewTransition來代替默認的淡入淡出效果應用到widget上,只需設置motionEffect_viewTransition,你就可以無限制地控制你想要應用的效果類型。
例如,要得到以下動畫。

你可以創(chuàng)建一個ViewTransition,并在MotionEffect中引用它。
在layout xml中:
<androidx.constraintlayout.helper.widget.MotionEffect
...
app:motionEffect_viewTransition="@+id/coolFade"/>
在motion scene中:
<ViewTransition android:id="@+id/coolFade">
<KeyFrameSet>
<KeyAttribute
motion:framePosition="20"
android:scaleX="0.1"
android:scaleY="0.1"
android:rotation="-90"
android:alpha="0" />
<KeyAttribute
motion:framePosition="80"
android:scaleX="0.1"
android:scaleY="0.1"
android:rotation="-90"
android:alpha="0" />
</KeyFrameSet>
</ViewTransition>
?本文譯自 https://github.com/androidx/constraintlayout/wiki/MotionEffect
?
向大家推薦下我的網站 https://xuyisheng.top/ 點擊原文一鍵直達
專注 Android-Kotlin-Flutter 歡迎大家訪問
往期推薦
更文不易,點個“三連”支持一下??
