AndroidAndroid专题UI

动画布局:MotionLayout用法解析,让你的布局运动起来!

2020-11-03  本文已影响0人  千夜零一

介绍

  动画布局MotionLayout是ConstraintLayout的子类,它具有ConstraintLayout的所有属性。同时MotionLayout支持在XML中完全描述一个复杂的动画,而不需要通过Java代码来实现。(有没有很开心!)
  话不多说,先看运行效果,再看代码学习起来!


效果预览


控件解析


用法

第一步:添加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">
        <!--自定义动画开始状态-->
        <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">
        <!--自定义动画结束状态-->
        <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
            <!--转换状态+定义延迟-->
        app:constraintSetStart="@+id/start"
        app:constraintSetEnd="@id/end"
        app:duration="1000">
        <OnClick
            app:clickAction="toggle"
            app:targetId="@+id/rect" />
        <KeyFrameSet></KeyFrameSet>
    </Transition>

</MotionScene>

大功告成!

上一篇下一篇

猜你喜欢

热点阅读