[英]Animate/translate view from position of other view
我有一個晶圓廠和可以容納一個片段的框架布局。
我正在嘗試制作翻譯動畫,以使我的框架布局從晶圓廠的位置開始,並在其原始位置結束。 (復雜布局,晶圓廠位於另一個xml文件中,但<include>
與框架位於相同的布局中)因此,這里的基本步驟2: 如何將FAB轉換為彈出菜單?
我努力了:
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="340"
android:fromYDelta="431"
android:toXDelta="0"
android:toYDelta="0"
android:duration="1000"
android:fillAfter="true" />
和
val anim = TranslateAnimation(340f, 0f, 431f, 0f)
與
myFab.setOnClickListener {
val frame = my_frame_im_about_to_fill_with_a_fragment
frame.startAnimation(anim)
}
所以我嘗試了從這些方法獲得的值
myFab.getLocationOnScreen()
myFab.getLocationInWindow()
兩種方法都給出(891, 1130)
。 我試過將它們插入或將其轉換為dp,這會使它更接近(盡管不是很接近)。
另一個奇怪的事情是,我認為如果我在動畫中使用絕對值,我會認為零將位於屏幕的左上方,但事實並非如此。 x: 0 y: 0
給我與0%,0%
和0%p,0%p
相同的結果。 它們都將視圖動畫化為xml中framelayout約束的左上角
如何將一個視圖從另一個視圖轉換為“自身”?
使用ConstraintLayout進行布局,將視圖約束放置到起始位置(這里,我將在單擊@+id/fab
后對@+id/view
進行動畫處理。動畫視圖必須是VISIBLE
或不INVISIBLE
GONE
會弄亂動畫。
<androidx.constraintlayout.widget.ConstraintLayout
/*constraint stuff*/>
<View
android:id="@+id/view"
android:layout_width="120dp"
android:layout_height="120dp"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginBottom="120dp"
app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
app:layout_constraintEnd_toEndOf="@+id/symbolList" />
</androidx.constraintlayout.widget.ConstraintLayout>
有幾種選擇:
在您的xml文件中,放置將在fab位置上動畫的View:
view = findViewById(R.id.view)
fab = findViewById(R.id.fab)
fab.setOnClickListener {
view.visibility = View.VISIBLE
val propertyX = PropertyValuesHolder.ofFloat(View.X, 0f)
val propertyY = PropertyValuesHolder.ofFloat(View.Y, 0f)
ObjectAnimator.ofPropertyValuesHolder(view, propertyX, propertyY).apply {
duration = 2000L
start()
}
}
或使用ViewPropertyAnimator(與上述XML相同)
fab.setOnClickListener { view.animate() .x(0f) .y(0f) .setDuration(2000L) .start() }
或手動使用TransitionManager,MotionLayout,場景api或為ConstraintSet設置動畫。
private fun startAnimation() { val animationEndConstraints = ConstraintSet().apply { clone(container) clear(button.id, ConstraintSet.START) clear(button.id, ConstraintSet.TOP) // instead of parent you can use fab.id connect(button.id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, 0) connect(button.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0) } TransitionManager.beginDelayedTransition(container) animationEndConstraints.applyTo(container) }
這種方法將允許將開始狀態指定為xml布局,將結束狀態指定為xml布局,但是您的控制較少。
與其他視圖位置:
fab.setOnClickListener {
view.animate()
.x(fab.left.toFloat())
.y(fab.top.toFloat())
.setDuration(2000L)
.start()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.