はじめに
MotionLayoutが発表されて随分経った。「Android Studio 4系が必須でMotion Editorが来るのを待っていた」という言い訳で長い間スルーしていたが、そろそろ4系が安定して来たという話をちらほら聞くのでちょっとさわってみた。結果、Motion Editorなくても全然xml tag手書きでいけるということがわかったのでメモを残す。
ちなみにさわったのはこちらのcodelab。
codelabs.developers.google.com
MotionLayoutの基本
ConstraintLayout
を継承したMotionLayout
をparent viewとするMotionLayout
のtag内にapp:layoutDescription="@xml/foo"
といったようにMotionScene
を定義したxmlファイル名を指定するMotionScene
にはTransition
とConstraintSet
を定義
Transition
-
Transition
のtag内にapp:constraintSetStart="@+id/start"
みたいな感じでanimationのstart/endのConstraintSet
を指定 - Animationの契機となる
OnClick
やOnSwipe
などはTransition
の中で定義する - animationのstart/endの間のPathを定義したい場合は
Transition
の中でKeyFrameSet
とその中にKeyPosition
を定義する -
KeyPosition
-
keyPositionType
でどのようにMotionが変化するか指定する - 各typeについてはここを参照
-
parentRelative
はscreenと同じく左上が(0, 0)
-
-
- animationのstart/endの間のview propertyを変えたい場合は
KeyAttribute
を定義する-
KeyAttribute
の中でCustomAttribute
を設定することができる -
CustomAttribute
のapp:attributeName
には対象クラスに定義されたsetter nameを指定する。(setXxxYyy()
を使いたい場合はapp:attributeName="XxxYyy"
になる。)
-
ConstraintSet
-
ConstraintSet
の中ではanimationしたいviewごとにConstraint
を定義 -
Constraint
のandroid:id
には対象のviewを指定 - layout fileに書いた各attributeはConstraintSetのxmlに定義したものに上書きされてしまう。 1そのため、
android:layout_width
とandroid:layout_height
を各Constraint
で指定する必要がある。
覚えておきたい便利な機能・Tips
app:motionDebug="SHOW_PATH"
をMotionLayout
のtagに入れることでmotionのpathをアプリ上で表示することができるtouchAnchorSide
は基本的に一直線に進む方向を指定する必要がある(そうでないとanimationがおかしくなる場合がある)が、複雑なpathを書きたい場合はどの方向にも一直線に進まないケースがある。その場合はinvisibleなviewを一つ作ってそいつをanchorにするとうまくいく。- あるいは
app:dragDirection
を追加で指定することで解決するかもしれない
- あるいは
- コードからmotionを動かしたいときは
MotionLayout#setProgress(float pos)
を使う - 既存のConstraintLayoutをMotionLayoutにconvertしたい場合は、下記手順で自動でconvertしてくれる
- ConstraintSetを使う時は全てのchildにidつけてやらないとDesign tabのpreviewもうまくrenderされない。またapp実行時に下記のRuntimeExceptionがthrowされる
java.lang.RuntimeException: All children of ConstraintLayout must have ids to use ConstraintSet