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
        }
    }
}
相关推荐
问心无愧05131 小时前
[GXYCTF2019]Ping Ping Ping
android·笔记
事圆则缓1 小时前
Kotlin 异步与并发:从一次搜索请求走到状态流
android·开发语言·kotlin
帅得不敢出门2 小时前
Android Framework定制卸载确认窗口
android
Android-Flutter3 小时前
Compose 什么叫重组?怎么样触发重组?
android·compose
硫酸锌013 小时前
安卓手机连接Windows电脑后通过DHCP服务为手机分配IP地址
android·windows·计算机网络
骑着蜗牛撵大象3274 小时前
设备监控数据存与查:Spring Boot 接入 TimescaleDB 超表的完整落地
android·spring boot·后端·springboot·时序数据库·es·设备监控
云贝贝贝4 小时前
MySQL 线上报 Lock wait timeout 别慌:6 招定位锁等待与死锁
android
mmsx4 小时前
Android 签名校验为什么能拦住二次打包:指纹与完整性校验
android·签名
jason.zeng@15022075 小时前
使用vscode+flutter开发android程序(入门)
android·vscode·flutter
事圆则缓5 小时前
Kotlin学习导航:从知识树走到项目与面试
android·开发语言·kotlin