java – Android设置视图位置 – setY vs setTop

我打算以编程方式移动按钮的位置.按钮处于相对布局中.我研究过并发现我们可以使用.setY()或.setTop().它们看起来应该是一样的.

但在我的情况下,.setTop()根本不会改变位置,而.setY()只能起作用.我不确定我做了什么误会,但对我来说这很奇怪.

有没有人可以正确解释setY()vs setTop()?
有什么不同?

这是layout.xml:

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
       android:layout_width="match_parent"
       android:layout_height="40dp"
       android:layout_marginLeft="10dp"
       android:layout_marginRight="10dp"/>
</RelativeLayout>

最佳答案 setY()和setTop()之间的主要区别在于setY()设置视图相对于可视区域的顶部偏移量,而setTop()设置视图相对于其父级的顶部偏移量.

Android documentation.

塞蒂()

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

机顶盒()

Sets the top position of this view relative to its parent.

点赞