我想将ImageView移到Button的中心。为此,我使用以下代码:
var leftPos = mButtonView.left.toFloat()
var rightPos = mButtonView.right.toFloat()
var topPos = mButtonView.top.toFloat()
var bottomPos = mButtonView.bottom.toFloat()
var centerX = (leftPos + rightPos)/2
var centerY = (topPos + bottomPos)/2
var soultoX = ObjectAnimator.ofFloat(mContentView, "x", centerX).apply {
duration = 1000
}
var soultoY = ObjectAnimator.ofFloat(mContentView, "y", centerY).apply {
duration = 1000
}
fun soulToButton() = AnimatorSet().apply {
play(soultoX).with(soultoY)
start()
}
在调用soulToButton()
时,mButtonView
不会移动到mContentView
中间的期望点,而是移动到屏幕的左上角。知道为什么吗?
答案 0 :(得分:0)
我认为问题是-在屏幕构建过程中找到Android View的坐标/大小。要尽快获取视图的坐标/大小,请将侦听器附加到其ViewTreeObserver。
例如:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val buttonView = btn
val contentView = img
object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
contentView.viewTreeObserver.removeOnGlobalLayoutListener(this)
var leftPos = buttonView.left.toFloat()
var rightPos = buttonView.right.toFloat()
var topPos = buttonView.top.toFloat()
var bottomPos = buttonView.bottom.toFloat()
var centerX = (leftPos + rightPos - contentView.width) / 2
var centerY = (topPos + bottomPos - contentView.height) / 2
var soultoX = ObjectAnimator.ofFloat(contentView, "x", centerX).apply {
duration = 1000
}
var soultoY = ObjectAnimator.ofFloat(contentView, "y", centerY).apply {
duration = 1000
}
fun soulToButton() = AnimatorSet().apply {
play(soultoX).with(soultoY)
start()
}
soulToButton()
}
}.run {
contentView.viewTreeObserver.addOnGlobalLayoutListener(this)
}
}