Reputation: 1297
Let's assume an ImageView, which when added to my layout(relative layout), with no scaling(the scale is 1). If I call getX(), it returns the correct X position.
However, if I now call setScaleX() with 2, and then call getX(), I get a totally different value. If I divide this value by the scale factor(2), it still doesn't give me the actual position. How do I get the actual position? Why is getX() returning absurdly large values which keep growing when the ImageView is scaled?
This is the case for the Y coordinate as well.
Upvotes: 3
Views: 3425
Reputation: 191
this is function from one of my projects I hope this help you:
private int[] getLocation(final View view) {
final int[] locations = new int[]{0, 0, 0, 0};
if (view != null) {
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int[] location = new int[2];
world_layout.getLocationInWindow(location);
locations[0] = location[0];//x postion
locations[1] = location[1];//y postion
locations[2] = view.getWidth();
locations[3] = view.getHeight();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
}
return locations;
}
Upvotes: 0
Reputation: 1297
Instead of using getX() and getY() to get the position of the view, I'm now using getMatrix(), and obtaining the translation values from this matrix. This seems to work well! It reports the correct X and Y values.
Upvotes: 1
Reputation: 1494
I got this problem when I tried to access getX(), getY() as well as other values like getWidth() or getHeight(), when I tried to access them from the "onCreate()", when I added a button and tried to access them from the onClick of the button it worked fine.
Upvotes: 0