我們知道志衍,要實現(xiàn)View的移動有很多種方式,比如offsetLeftAndRight()聊替、layout()楼肪、translationX/Y、X/Y惹悄、LayoutParams等等春叫,其實大差不大,都是通過偏移量來重新計算位置泣港,且x = left + translationX ; y = top + translationY暂殖。但其中translationX/Y就讓我有點困惑了,我們先看看用法:
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
if (event == null) return false
var downX = 0f
var downY = 0f
when (event.action) {
MotionEvent.ACTION_DOWN -> {
downX = event.x
downY = event.y
alpha = 1f
}
MotionEvent.ACTION_MOVE -> {
//方法1
//offsetLeftAndRight((event.x - downX).toInt())
//offsetTopAndBottom((event.y - downY).toInt())
//方法2
//用translation來更新位置的話当纱,就得加上原先的translation
//也就是說每次移動translation都生效了呛每,因此就得用原來的translation加上當(dāng)前
//move的差值?
Log.d("DragView", "offsetX = ${event.x - downX}")
Log.d("DragView", "offsetY = ${event.y - downY}")
Log.d("DragView", "translationX_old = $translationX")
translationX += event.x - downX
translationY += event.y - downY
Log.d("DragView", "translationX_now = $translationX")
}
MotionEvent.ACTION_UP -> {
animate().setInterpolator(DecelerateInterpolator())
.x(-(width / 2).toFloat())
.alpha(0.5f)
.start()
}
}
return true
}
主要在ACTION_MOVE中來處理View的移動,但event.x - downX算的是當(dāng)前位置和ACTION_DOWN也就是這一事件序列剛開始點擊位置的偏移量惫东,但是更新translationX/Y的時候卻需要加上原本的translation莉给,有點讓人費解,mark一下廉沮。