Android Koitlin:翻译视图上的动画不起作用

问题描述 投票:0回答:1

我正在研究一个Android Kotlin项目。我正在对视图应用动画。从基础开始,我尝试使从屏幕底部到屏幕中心的图像视图动画化。

我有一个带有以下代码的XML布局。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:background="@color/colorPrimaryDark"
    tools:context=".MainActivity">

    <LinearLayout
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/main_image_logo"
            android:src="@drawable/memento_text_logo"
            android:layout_width="@dimen/main_logo_image_width"
            android:layout_height="wrap_content" />
        <TextView
            android:textColor="@android:color/white"
            android:id="@+id/main_tv_slogan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/main_slogan"
            />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

我在活动中使用以下代码对从底部到中心(原始位置)的徽标图像进行动画处理。

private fun animateMainLogo() {
        val valueAnimator = ValueAnimator.ofFloat(0f, main_image_logo.y)

        valueAnimator.addUpdateListener {
            val value = it.animatedValue as Float
            main_image_logo.translationY = value
        }

        valueAnimator.interpolator = LinearInterpolator()
        valueAnimator.duration = 1000
        valueAnimator.start()
    }

当我运行代码时,它没有使视图动画化。它就在那里而且是静态的。我的代码有什么问题,我该如何解决?

android animation android-animation
1个回答
0
投票
    // move declaration outside of method to prevent Garbage Collector to collect it
    private val valueAnimator = ValueAnimator.ofFloat(0f, main_image_logo.y).apply{
             interpolator = LinearInterpolator()
             duration = 1000
    }

   override fun onCreate(savedInstanceState: Bundle){
             super.onCreate(saveInstanceState)

             valueAnimator.addUpdateListener {
                  val value = it.animatedValue as Float
                  main_image_logo?.translationY = value
             }
   }



    private fun animateMainLogo() {
            valueAnimator.start()
    }
© www.soinside.com 2019 - 2024. All rights reserved.