If I have a certain View on the layout (ImageView
, for example), is it possible to find the distance from the bottom border of the View to the bottom of the phone screen?
Thanks.
If I have a certain View on the layout (ImageView
, for example), is it possible to find the distance from the bottom border of the View to the bottom of the phone screen?
Thanks.
// instantiate DisplayMetrics
DisplayMetrics dm = new DisplayMetrics();
// fill dm with data from current display
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
// loc will hold the coordinates of your view
int[] loc = new int[2];
// fill loc with the coordinates of your view (loc[0] = x, looc[1] = y)
yourImageView.getLocationOnScreen(loc);
// calculate the distance from the TOP(its y-coordinate) of your view to the bottom of the screen
int distance = dm.heightPixels - loc[1];
You need to wait for the callback when the layout has been placed with children views. This is the listener you need to add to your root view in order to calculate the coordinates for your image. Otherwise it will return 0.
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
imageView.getLocationOnScreen(locations);
int x = locations[0];
int y = locations[1];
}
});
And you have to get the width and height of the screen using getWindowManager().
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Now you have View x and y locations on the screen, screen width and height. You can calculate the distance using those points.
View.getLocationOnScreen() would give you the y. Add view width and padding to it to get the bottom most point of view.
getContext().getResources().getDisplayMetrics().heightPixels would give you height of screen in pixels.
Subtract the two and you get the difference in pixels.
You can find it by following way.
Use this to get view position on screen
View.getLocationOnScreen()
and/or getLocationInWindow().
get Screen Display
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Then calculate (height-view.y-location )