Android中获取当前屏幕的宽高工具类

获取屏幕的宽高,可以直接使用的工具类

添加了不同版本的适配,可以获取到屏幕总高度、屏幕可用高度(排除状态栏与导航栏)等

kotlin 复制代码
object ScreenSizeUtil {

    /**
     *  @describe: 获取屏幕总高度,包括状态栏、导航栏
     *  @params:
     *  @return:
     */
    fun getScreenTotalHeight(context: Context): Int {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { //30以上的适配
           val bounds = windowManager.maximumWindowMetrics.bounds
            bounds.height()
        } else { //低版本适配
            val meterics = DisplayMetrics()
            windowManager.defaultDisplay.getMetrics(meterics)
            meterics.heightPixels
        }
    }


    /**
     *  @describe: 获取屏幕总宽度,包含所有系统栏
     *  @params: 
     *  @return: 
     */
    fun getScreenTotalWidth(context: Context): Int {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val windowMetrics = windowManager.maximumWindowMetrics
            val bounds = windowMetrics.bounds
            bounds.width()
        } else {
            val metrics = DisplayMetrics()
            windowManager.defaultDisplay.getMetrics(metrics)
            metrics.widthPixels
        }
    }

    /**
     *  @describe: 获取应用可用高度,不含状态栏、导航栏
     *  @params:
     *  @return:
     */
    fun getAppUsableHeight(activity: Context): Int {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val windowManager = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val windowMetrics = windowManager.currentWindowMetrics
            val insets = windowMetrics.windowInsets
                .getInsetsIgnoringVisibility(android.view.WindowInsets.Type.systemBars())
            // 应用高度 = 窗口高度 - 状态栏高度 - 导航栏高度
            windowMetrics.bounds.height() - insets.top - insets.bottom
        } else {
            // 低版本:通过 DecorView 获取可视区域
            val decorView = (activity as android.app.Activity).window.decorView
            val outRect = Rect()
            decorView.getWindowVisibleDisplayFrame(outRect)
            outRect.bottom - outRect.top
        }
    }
}
相关推荐
booboosui6 小时前
清单 40 件是硬上限:过期的活挂了 48 小时才被打标记
android
FlightYe6 小时前
linux系统编程(二十一):C 语言常见坑
android·linux·运维·服务器·c语言·音视频
方白羽7 小时前
SP vs DataStore:解锁 Android 本地存储的并发秘密
android·app·客户端
GY-937 小时前
【Android】View和Componse
android
王二蛋与他的张大花9 小时前
后台内存 827MB,我一行业务逻辑都没改就砍到 100MB
android·flutter·性能优化
Paper_Love9 小时前
android安全公告网站
android
StarsGreen13 小时前
Android ADB(Android Debug Bridge)命令详解
android
阿健君13 小时前
现代 Android 屏幕适配完全指南
android·kotlin
软件交付观察室15 小时前
用户关掉手机定位权限后,原生App还能显示哪些位置?
android·ios·移动开发
黄林晴15 小时前
Jetpack Compose 1.13.0 来了:大量 API 弃用,表单代码要重构
android·android jetpack