setX(), setTranslationX(), setY(), and setTranslationY()

情到浓时终转凉″ 提交于 2021-02-06 08:03:08

问题


What are the differences between setX(), setY(), and setTranslationX(), setTranslationY()? Are they setting offsets on existing coordinates or setting absolute positions?

If they are setting absolute coordinates won't that conflict with the parent layout's constraints?

Say we have something like | View 1 | View 2 | View 3|

in a LinearLayout, what if we did view2.setX(0); or view2.setTranslationX(0); would view 2 overlap view 1 or push view 1 to the side?

Likewise what if we had a child of a RelativeLayout that had alignParentBottom set to true but we manually set that child's y coordinate to 0 in code. Which layout rule wins?

Essentially, I'm confused about how manual coordinates affect the layout rules of the container and also the difference between translation and X/Y. I apologize in advance if this seems trivial but I am new to Android having come from iOS.


回答1:


From the docs, setTranslationX is:

Sets the horizontal location of this view relative to its left position. This effectively positions the object post-layout, in addition to wherever the object's layout placed it.

And setX is:

Sets the visual x position of this view, in pixels. This is equivalent to setting the translationX property to be the difference between the x value passed in and the current left property.

Thus you can think of setTranlsationX as a relative offset: move 3 pixels left of where you normally would be. And setX is a fixed position: move whatever you have to so that you end up drawing at coordinate X.




回答2:


setX/Y set absolute position from 0,0 screen. setTranlsationX/Y set position from default position of view in layout.

enter image description here




回答3:


Setting X and Y sets the position of the view relative to the parent view's top left corner (not the absolute position on the screen). Setting the translation moves the view relative to where the parent laid it out. (The parent laid the view out at (left, top).)

enter image description here



来源:https://stackoverflow.com/questions/33701657/setx-settranslationx-sety-and-settranslationy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!