Reputation: 1011
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.
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.
Is there anybody who can explain setY()
vs setTop()
correctly?
What is the difference?
This is 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>
Upvotes: 9
Views: 11956
Reputation: 34341
You can notice that setTop()
doesn't have effect unlike setY()
. The reason is that a field mTop
is being changed by layout()
. The simplest way to see a changed mTop
is to set a top margin.
Upvotes: 1
Reputation: 9149
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.
From the Android documentation.
setY()
Sets the visual y position of this view, in pixels. This is equivalent to setting the
translationY
property to be the difference between they
value passed in and the currenttop
property.
setTop()
Sets the top position of this view relative to its parent.
Upvotes: 6