![](/img/trans.png)
[英]Android View with a translate animation - positioning is not working as expected
[英]Android Kotlin: Translate animation on view is not working
我正在研究 Android Kotlin 項目。 我在視圖上應用 animation。 從基礎開始,我試圖將圖像視圖從屏幕底部動畫到屏幕中心。
我有一個帶有以下代碼的 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()
}
當我運行代碼時,它不會為視圖設置動畫。 它就在它所在的位置和 static。 我的代碼有什么問題,我該如何解決?
布局中視圖的translationY
為0。如果要將其從底部動畫到當前position - 您應該將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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.