android - Android Kotlin:在视图上翻译动画不起作用
问题描述
我正在开发一个 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()
}
当我运行代码时,它不会为视图设置动画。它就在它所在的地方并且是静态的。我的代码有什么问题,我该如何解决?
解决方案
translationY
布局中的视图为 0。如果您想将其从底部设置为当前位置 - 您应该将translationY
值从某个正值更改为 0。
private fun animateLogo() {
val translationYFrom = 400f
val translationYTo = 0f
val valueAnimator = ValueAnimator.ofFloat(translationYFrom, translationYTo).apply {
interpolator = LinearInterpolator()
duration = 1000
}
valueAnimator.addUpdateListener {
val value = it.animatedValue as Float
main_image_logo?.translationY = value
}
valueAnimator.start()
}
同样的事情可以这样做:
private fun animateLogo() {
main_image_logo.translationY = 400f
main_image_logo.animate()
.translationY(0f)
.setInterpolator(LinearInterpolator())
.setStartDelay(1000)
.start()
}
将这条线添加到LinearLayout
并且ConstraintLayout
因为没有它们会在动画视图超出边界LinearLayout
时剪切部分动画视图。LinearLayout
android:clipChildren="false"
android:clipToPadding="false"
推荐阅读
- mongodb - 如何区分价值……猫鼬
- python - Tobii 眼动仪
- r - 如何在数据框中从数字替换为单词?
- c# - 如何访问一维数组中的多维?
- kubernetes - 如何在 Kubernetes 中移除(删除)注解
- python - Pandas read_csv 没有读取文件中的所有行
- ruby-on-rails - Rails 嵌套表单 - 从 Club 创建新会议
- c++ - 以类似表格的顺序显示来自 for 循环的值以使其更加清晰和干净?
- javascript - 如何使用带有 PHP 的 javascript 滚动到下一个 div?
- groovy - 如何从 Groovy 中的静态超类方法引用子类