首页 > 解决方案 > 约束布局中的 Motionlayout OnClick 问题

问题描述

我使用运动布局尝试了一些很酷的过渡。它工作得很好。但是当我尝试使用 onClick 时,点击事件会影响整个屏幕,而不是特定的小部件。

XML:

    <?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/motionLayout_container"
    app:layoutDescription="@xml/button_motionscene">



    <View
        android:id="@+id/newBtn"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:background="@color/colorPrimaryDark"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"

        />

</androidx.constraintlayout.motion.widget.MotionLayout>

动态场景文件:

<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@+id/start"
        motion:duration="1000">

        <OnClick motion:motionTarget="@id/newBtn"
            motion:clickAction="transitionToEnd"
            />
    </Transition>



    <ConstraintSet android:id="@+id/start">
        <Constraint android:id="@id/newBtn">
            <Layout
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:layout_marginStart="8dp"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintTop_toTopOf="parent" />
        </Constraint>
    </ConstraintSet>

    <ConstraintSet
        android:id="@+id/end"
        motion:deriveConstraintsFrom="@id/start">

        <Constraint android:id="@id/newBtn">
            <Layout
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:layout_marginEnd="8dp"
                motion:layout_constraintEnd_toEndOf="parent" />
        </Constraint>
    </ConstraintSet>




</MotionScene>

依赖项:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'androidx.annotation:annotation:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
}

无论我在屏幕中的哪个位置单击它都会显示动画。我不知道我犯了什么错误。

标签: androidandroid-constraintlayoutandroid-motionlayout

解决方案


取决于您使用的库的版本。例如,在 beta2 中,它targetId是用于此目的的属性(而不是motionTarget你有)


推荐阅读