如何获取屏幕宽度和高度 [英] How to get screen width and height

查看:152
本文介绍了如何获取屏幕宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用下面的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+,你可以使用<一个href="http://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point)"><$c$c>getRealSize:

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

如果你想在可用的窗口大小,你可以使用<一个href="http://developer.android.com/reference/android/view/Window.html#getDecorView()"><$c$c>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);

<一个href="http://developer.android.com/reference/android/view/Display.html#getRealMetrics(android.util.DisplayMetrics)"><$c$c>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);

这篇关于如何获取屏幕宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆