我有一个Fragment
和viewBinding
可用。我想在我的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
}
获取x
和y
的onViewCreated
上的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)
}
}