在启动阶段以编程方式定位或动画化视图



我有一个FragmentviewBinding可用。我想在我的ConstraintLayout中重新定位View

假设我有三个视图(RedView, GreenView和BlueView), RedView和GreenView的位置是固定的,当我想要时,BlueView应该将自己定位在其中一个固定位置的视图上。.

场景:当我启动应用程序时,将BlueView放置在RedView上。

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.blue.alpha = 1f // this changes alpha value
binding.blue.x = binding.red.x // this won't change x position
binding.blue.y = 200f // this will change y position
}

获取xyonViewCreated上的viewBinding值不会返回任何东西。

然而,如果我通过Event动画它,它工作。

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
...
binding.redView.setOnClickListener{ view ->
animateBlueView(view).start() // x and y position will be changed
}
}
fun animateBlueView(view: View): AnimatorSet {
val x = ValueAnimator.ofFloat(binding.blue.x, view.x).apply {
duration = 300
addUpdateListener {
binding.blue.x = animatedValue as Float
}
}
val y = ValueAnimator.ofFloat(binding.blue.y, view.y).apply {
duration = 300
addUpdateListener {
binding.blue.y = animatedValue as Float
}
}
return AnimatorSet().apply {
play(x).with(y)
}
}

当我尝试以编程方式触发onViewCreated中的动画时,动画不会启动。

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
...
animateBlueView(binding.red).start()
}
我错过了一些基本的东西,但我不知道它是什么。有人能解释一下发生了什么,我应该注意什么吗?
fun animateBlueView(view: View): AnimatorSet {
val x = ValueAnimator.ofFloat(binding.blue.x, view.x).apply {
duration = 300
addUpdateListener {
binding.blue.x = animatedValue as Float
}
}

val y = ValueAnimator.ofFloat(binding.blue.y, view.y).apply {
duration = 300
addUpdateListener {
binding.blue.y = animatedValue as Float
}
}

return AnimatorSet().apply {
play(x).with(y)
}
}

最新更新