1

I would like to get position X or Y of view (ie button) programmatically but in solutions from link (https://blog.takescoop.com/android-view-measurement-d1f2f5c98f75) returned values are wrong.

I need this to restrain y in animation for clamp function.

Also I have problems to get height and width programmatically. I can get view like here (https://stackoverflow.com/a/24035591/9498656 by view.post(new Runnable()) but like before values are wrong.

problem: animated view with restrictions on other view Y

Could someone explain how get X Y height width for different screens?

2 Answers2

0

To get the posX and posX of a view relative to the screen of the device you can use;

int location[] = new int[2];
view.getLocationOnScreen(location);
int posX = location[0];
int posY = location[1];

To get height and width of a view you can use

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            view.getHeight(); //height is ready
            view.getWidth(); //width is ready
        }
    });

Don't forget to remove the listener of ViewTreeObser to your view by calling view.getViewTreeObserver().removeOnGlobalLayoutListener(this);

Anis MARZOUK
  • 266
  • 2
  • 9
0

Here is what I would do:

//Get screen size.
    WindowManager wm = getWindowManager();
    Display disp = wm.getDefaultDisplay();
    Point size = new Point();
    disp.getSize(size);
    int screenWidth = size.x;
    int screenHeight = size.y;

Also, take into consideration that most of the time, the size of the window is not equal to the size of the screen since you have to account for the size in pixels of the buttons at the button of the screen (menu, back, opened apps).

Hope it helps!

ChanceVI
  • 200
  • 1
  • 10