如何获取屏幕宽度和高度宽度、屏幕、高度

由网友(被狗追过的夏天)分享简介:我试图用下面的code获得屏幕宽度和高度的Andr​​oid应用程序开发:I tried to use following code to get screen width and height in android app development:Display display = getWindowManage...

我试图用下面的code获得屏幕宽度和高度的Andr​​oid应用程序开发:

I tried to use following code to get screen width and height in android app development:

Display display = getWindowManager().getDefaultDisplay(); 
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();

但我得到的 NullPointerException异常我显示,为什么呢?如何让屏幕宽度和高度呢?

but I got NullPointerException for my display, why? how to get screen width and height then?

推荐答案

如果你调用一个活动的这个之外,你需要传递的情况下(或者通过一些其他的调用得到它)。然后用它来让你的显示器的指标:

If you're calling this outside of an Activity, you'll need to pass the context in (or get it through some other call). Then use that to get your display metrics:

DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;

更新:通过API级别17+,你可以使用getRealSize:

Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);

如果你想在可用的窗口大小,你可以使用getDecorView从实际显示尺寸减去装修视图大小来计算可用面积:

If you want the available window size, you can use getDecorView to calculate the available area by subtracting the decor view size from the real display size:

Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);

Rect windowSize = new Rect();
ctivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(windowSize);

int width = displaySize.x - Math.abs(windowSize.width());
int height = displaySize.y - Math.abs(windowSize.height());
return new Point(width, height);

getRealMetrics也可以工作(需要API级别17+),但我还没有尝试过:

getRealMetrics may also work (requires API level 17+), but I haven't tried it yet:

DisplayMetrics metrics = new DisplayMetrics();
activity.GetWindowManager().getDefaultDisplay().getRealMetrics(metrics);
阅读全文

相关推荐

最新文章