如何获取从视图到手机底部的距离?

7
如果在布局上有一个特定的视图(例如ImageView),是否可能找到该视图底部边界到手机屏幕底部的距离?
谢谢。
4个回答

11
// 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];

一些解释会让你的答案更好。 - NathanOliver
在我的情况下,似乎只有getWindowManager().getDefaultDisplay().getRealSize能够在全屏时包含工具栏大小。 - 林果皞
如果我想要从视图底部到屏幕底部的距离怎么办? - IgorGanapolsky

4

当布局与子视图放置完毕后,您需要等待回调。这是您需要添加到根视图的监听器,以便为您的图像计算坐标。否则它将返回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];
        }
    });

您需要使用getWindowManager()获取屏幕的宽度和高度。

  Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

现在你可以获取屏幕上视图X和Y坐标,屏幕的宽度和高度。你可以使用这些点计算距离。


1

View.getLocationOnScreen() 将给出 y 坐标。将视图宽度和填充添加到其中,以获取视图的底部最低点。

getContext().getResources().getDisplayMetrics().heightPixels 将给出屏幕高度(以像素为单位)。

两者相减即可获得像素差异。


1

您可以按以下方式找到它。

使用此方法获取屏幕上的视图位置

View.getLocationOnScreen() 和/或 getLocationInWindow().

获取屏幕显示

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

然后计算 (height-view.y-location )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接