0

I have a RelativeLayout in which i have one ImageButton. I need the position parametres of this item and I don,t know how to get them.

I have try with:

ImageButton user = (ImageButton) findViewById(R.id.User);
int x =user.getTop();
int y =user.getLeft();

But the result is allways 0;

Thank you.

Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265
  • Why do you need this position? What are you trying to achieve? – Aleks G Mar 13 '12 at 11:27
  • In fact, I have 3 imagebuttons. I would like to change their position on scroll. My scroll works well and in onCreate, I would like to catch the buttons position. – Milos Cuculovic Mar 13 '12 at 11:29

3 Answers3

4

I think you are invoking this method when the layout is being drawn, instead you should use:

ViewTreeObserver observer = user.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        //in here, place the code that requires you to know the dimensions.
        //Place your code here
    }
}
jeet
  • 29,001
  • 6
  • 52
  • 53
0

getTop() and getLeft() returns you the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent. See here under the point position. Try something like:

user.getParent().getLeft();

hope that helps!

Chris
  • 4,403
  • 4
  • 42
  • 54
0

Because your ImageButton was not calculated its position ready on that time.

see How to get an Android widget's size after layout is calculated?

Do not try to get position in onCreate(), that always returns 0.

Community
  • 1
  • 1
chengbo
  • 5,789
  • 4
  • 27
  • 41