Android 设置视图位置 - setY vs setTop [英] Android set view position - setY vs setTop

查看:41
本文介绍了Android 设置视图位置 - setY vs setTop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was going to move the button's position programmatically. Button is in relative layout. I'd researched and found that we can use .setY() or .setTop(). It looks like they should work the same.

但就我而言,.setTop() 根本不会改变位置,而 .setY() 仅起作用.我不确定我误解了什么,但这对我来说很奇怪.

But in my case, .setTop() does not change the position at all and .setY() works only. I'm not sure what I did misunderstand but it's very weird for me.

有没有人可以正确解释 setY()setTop() ?有什么区别?

Is there anybody who can explain setY() vs setTop() correctly? What is the difference?

这是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() 设置视图相对于其父视图的顶部偏移.

The main difference between setY() and setTop() is that setY() sets the top offset of the view relative to the visual area, whereas setTop() sets the top offset of the view relative to its parent.

来自 Android 文档.

setY()

设置此视图的视觉 y 位置,以像素为单位.这相当于将 translationY 属性设置为传入的 y 值与当前 top 属性之间的差值.

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.

setTop()

设置此视图相对于其父视图的顶部位置.

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

这篇关于Android 设置视图位置 - setY vs setTop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆