作者:opLW
目录
1.例子
2.x和y
3.translationX和translationY
4.left, right, top, bottom
5.rawX和rawY
6.一张图记住这些
1.例子
通过一个动画例子看看在这个过程中各项值的情况。
val root = inflater.inflate(R.layout.fragment_favourite, container, false)
val fatherView = root.findViewById<LinearLayout>(R.id.father_view)
val childView = root.findViewById<TextView>(R.id.child_view)
childView.viewTreeObserver.addOnGlobalLayoutListener {
val translationX = ObjectAnimator.ofFloat(childView, "translationX", 0f, fatherView.width.toFloat())
val translationY = ObjectAnimator.ofFloat(childView, "translationY", 0f, fatherView.height.toFloat())
val listener = object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) {}
override fun onAnimationEnd(animation: Animator?) {
Log.i("animator", "end")
printMsg(childView)
}
override fun onAnimationCancel(animation: Animator?) {}
override fun onAnimationStart(animation: Animator?) {
Log.i("animator", "start")
printMsg(childView)
}
}
val set = AnimatorSet().also {
it.playTogether(translationX, translationY)
it.duration = 3000
it.addListener(listener)
it.startDelay = 2000
}
set.start()
}
private fun printMsg(view: View) {
val x = view.x
val y = view.y
val translationX = view.translationX
val translationY = view.translationY
val left = view.left
val right = view.right
val bottom = view.bottom
val top = view.top
Log.i("x", "" + x)
Log.i("y", "" + y)
Log.i("translationY", "" + translationX)
Log.i("translationX", "" + translationY)
Log.i("left", "" + left)
Log.i("right", "" + right)
Log.i("bottom", "" + bottom)
Log.i("top", "" + top + "\n")
}
结果如下:
- 由例子可见在移动的过程中left,right,bottom和top是不变的,而x,y,translationX,translationY则处于变化状态。
- 总结: 属性动画改变的只是translationX和translationY的值,而left,right,bottom和top只跟布局相关,跟动画无关。
2. x和y
- x和y,translationX和translationY都是API11(android3.0)之后引入的(引入时间跟属性动画一样,应该是为属性动画服务的 😄)
- x,y分别表示子控件左上角 相对父容器的x坐标和y坐标。
- 与left和top的区别:
- x = left + translationX
- y = top + translationY
3. translationX和translationY
- translationX 和 translationY 是 View 左上角相对父容器左上角的偏移量,translationX 和 translationY 默认值都为 0。
4. left, right, top, bottom
- View 的位置主要由它的四个顶点的位置来决定
- left: View 左上顶点相对于父容器的横坐标
- right: View 右下顶点相对于父容器的横坐标
- top: View 左上顶点相对于父容器的纵坐标
- bottom: View 右下顶点相对于父容器的纵坐标
- 可以通过对应的getter和setter来获取和修改值。
5. rawX和rawY
-
View本身没有这些概念,这些概念一般出现在点击事件MotionEvent中。
-
MotionEvent中有getX(), getY(), getRawX()和getRawY()
- getX(), getY(): 获得触摸点的位置,此时取得的x和y是相对于被触摸控件本身的左上角。
- getRawX()和getRawY(): 获得触摸点的位置,此时取得的x和y是相对于屏幕左上角的。
6.一张图记住这些
注意: 白色为控件一开始的位置,黄色为控件移动结束的位置
- 1 控件的top
- 2 控件的left
- 3 控件的bottom
- 4 控件的right
- 5 控件移动的translationX(上面图画错了,translationX,translationY的参照点默认为控件中心点)
- 6 控件移动的translationY
- 7 控件的y,即view的getY()
- 8 控件的x,即view的getX()
- 9 点击事件的y,即MotionEvent的getY()
- 10 点击事件的x,即MotionEvent的getX()
- 11 点击事件的rawY,即MotionEvent的getRawY()
- 12 点击事件的rawX,即MotionEvent的getRawX()
万水千山总是情,麻烦手下别留情。
如若讲得有不妥,文末留言告知我,
如若觉得还可以,收藏点赞要一起。