如何获取可用显示尺寸的绝对像素高度与宽度
Android 获取屏幕绝对像素宽高实现方案
与目标代码效果完全一致的基础实现
你提到的activity.getResources().getDisplayMetrics().heightPixels 和 activity.getResources().getDisplayMetrics().widthPixels 本身就是官方提供的标准实现,不同场景的写法如下:
Java 版本
// Activity 内部直接调用 int heightPixels = getResources().getDisplayMetrics().heightPixels; int widthPixels = getResources().getDisplayMetrics().widthPixels; // 全局工具类写法 public class ScreenUtils { public static int getHeightPixels(Context context) { return context.getResources().getDisplayMetrics().heightPixels; } public static int getWidthPixels(Context context) { return context.getResources().getDisplayMetrics().widthPixels; } }
Kotlin 版本
// Activity 内部直接调用 val heightPixels = resources.displayMetrics.heightPixels val widthPixels = resources.displayMetrics.widthPixels // 全局扩展函数写法 val Context.screenHeightPx: Int get() = resources.displayMetrics.heightPixels val Context.screenWidthPx: Int get() = resources.displayMetrics.widthPixels
注意事项与高版本兼容方案
- 上述基础实现获取的是包含系统状态栏、导航栏在内的整块屏幕物理像素,如果你需要获取应用可绘制的可用区域,需要适配Android 11及以上的新API
- Android 11(API 30)开始,
Display相关的旧方法被标记为废弃,官方推荐使用WindowManager的WindowMetricsAPI获取屏幕尺寸,兼容写法如下:
兼容全版本的可用区域尺寸获取
public static Pair<Integer, Integer> getScreenSize(Activity activity) { int height, width; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { WindowMetrics metrics = activity.getWindowManager().getCurrentWindowMetrics(); Rect bounds = metrics.getBounds(); height = bounds.height(); width = bounds.width(); } else { DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics); height = metrics.heightPixels; width = metrics.widthPixels; } return new Pair<>(height, width); }
fun Activity.getScreenSize(): Pair<Int, Int> { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val bounds = windowManager.currentWindowMetrics.bounds bounds.height() to bounds.width() } else { val metrics = DisplayMetrics() @Suppress("DEPRECATION") windowManager.defaultDisplay.getRealMetrics(metrics) metrics.heightPixels to metrics.widthPixels } }
- 上述兼容方案返回的尺寸会自动适配多窗口、折叠屏等场景,返回当前应用窗口的实际可用像素值,适配绝大多数业务需求
- 若需要兼容API 16及更低版本,将
getRealMetrics替换为getMetrics即可,仅部分老旧异形屏设备会出现尺寸偏差
内容的提问来源于stack exchange,提问作者Raj Bhagat
相关产品推荐
相关产品推荐

