Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get distance from the View to a phone bottom?

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.

like image 742
Mark Korzhov Avatar asked Aug 06 '15 09:08

Mark Korzhov


People also ask

How do you calculate km distance?

To solve for distance use the formula for distance d = st, or distance equals speed times time. Rate and speed are similar since they both represent some distance per unit time like miles per hour or kilometers per hour. If rate r is the same as speed s, r = s = d/t.


3 Answers

// 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];
like image 139
Omar Abdan Avatar answered Oct 20 '22 06:10

Omar Abdan


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.

like image 39
Saritha G Avatar answered Oct 20 '22 07:10

Saritha G


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.

like image 27
Prateek Avatar answered Oct 20 '22 05:10

Prateek