ConstraintLayout に MotionLayoutが追加されたので早速触ってみることにしました。
サンプルソースと動画を載せていますのでご参考下さい。
なお、本記事を投稿時点ではまだBeta版のため、今後変更が入る可能性があります。
サンプルソース
やることは以下です。
・build.gradle に constraintlayout:2.0.0を追加
・ConstraintLayout を MotionLayoutに変更
・MotionSceneのレイアウトを作成
build.gradle
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta5'
activity_main.xml
<androidx.constraintlayout.motion.widget.MotionLayout android:id="@+id/motion_layout" 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/scene_01" tools:context=".MainActivity"> <View android:id="@+id/move_left_right_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#00FF00" /> </androidx.constraintlayout.motion.widget.MotionLayout>
scene_01.xml
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android" xmlns:motion="http://schemas.android.com/apk/res-auto"> <Transition motion:constraintSetStart="@id/start" motion:constraintSetEnd="@id/end"> <OnSwipe motion:touchAnchorId="@id/move_left_right_view" motion:dragDirection="dragRight" motion:touchAnchorSide="right"/> </Transition> <ConstraintSet android:id="@+id/start"> <Constraint android:id="@id/move_left_right_view" android:layout_width="128dp" android:layout_height="128dp" motion:layout_constraintTop_toTopOf="parent" motion:layout_constraintBottom_toBottomOf="parent" motion:layout_constraintStart_toStartOf="parent" /> </ConstraintSet> <ConstraintSet android:id="@+id/end"> <Constraint android:id="@id/move_left_right_view" android:layout_width="64dp" android:layout_height="64dp" motion:layout_constraintEnd_toEndOf="parent" /> </ConstraintSet> </MotionScene>
上記のコードで左右移動するサンプル動作が確認できます。
■ポイント①
・新規作成したxmlファイルを指定します。
app:layoutDescription=”@xml/scene_01″
■ポイント②
・ConstraintSetで開始位置、終了位置を定義
・Transition で constraintSetStartとconstraintSetEndを用いて開始位置、終了位置を指定する
・Transition で OnSwipeを定義する。ここで指定した操作を行うことで動作が行える
サンプル動作
最後にサンプル動画を載せておきます。