如何从屏幕的底部到顶部为ConstraintLayout设置动画?

时间:2017-07-22 04:58:12

标签: android animation kotlin android-animation android-constraintlayout

我一直在寻找一种最简单的方法,使用ConstraintLayout从A点到B点对象进行动画处理,并能够改变其持续时间和加速度。例如,在屏幕上设置约束的情况下,将布局/视图从屏幕底部移动到其预期位置。我无法找到如何对ConstraintLayout的对象执行此操作。任何人都可以指出我正确的方向?感谢。

1 个答案:

答案 0 :(得分:10)

将此xml作为内容视图:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/constraint_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>

这在活动中:

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.item)

        val constraintLayout = findViewById(R.id.constraint_layout) as ConstraintLayout
        val button = findViewById(R.id.button)

        button.setOnClickListener {
            val constraintSet = ConstraintSet()
            constraintSet.clone(constraintLayout)
            constraintSet.setVerticalBias(R.id.button, 1.0f)
            constraintSet.setHorizontalBias(R.id.button, 1.0f)

            val transition = AutoTransition()
            transition.duration = 1500
            transition.interpolator = AccelerateDecelerateInterpolator()

            TransitionManager.beginDelayedTransition(constraintLayout, transition)
            constraintSet.applyTo(constraintLayout)
        }
    }
}

将导致此输出:

enter image description here

有关详细信息,请参阅this articlethis presentation