8

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>
technophyle
  • 7,972
  • 6
  • 29
  • 50
Capella
  • 881
  • 3
  • 19
  • 32

2 Answers2

6

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 the y value passed in and the current top property.

setTop()

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

technophyle
  • 7,972
  • 6
  • 29
  • 50
  • thank you for your answer based on Android documentation. Could you provide me an example that shows the difference of these functions exactly? – Capella Sep 30 '16 at 20:50
1

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.

yoAlex5
  • 29,217
  • 8
  • 193
  • 205