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
        }
    }
}
相关推荐
ue星空20 分钟前
第一个安卓程序
android
淡淡的香烟21 分钟前
Androidiot蓝牙配网简单封装
android·物联网
gxgldyh24 分钟前
Android Framework源码解析(九):App进程诞生全流程——从AMS请求到Zygote fork源码深度拆解
android·framework·zygote·android 启动流程·android app创建流程
牛哇网络工作室7 小时前
UnityHDRP写实数字人全流程基础5—语音输入和语音识别
android·unity·c#·游戏引擎·aigc·语音识别·xcode
一笑的小酒馆8 小时前
Androidiot蓝牙配网简单封装
android
愚公搬代码11 小时前
【愚公系列】《Android应用案例开发大全》016-LBS类应用掌上杭州(辅助工具类的开发)
android·前端
g105655913912 小时前
LAMP博客平台Wordpress实战
android·mysql·nginx·php
hunterandroid13 小时前
[Android 从零到一] Compose LazyColumn 性能优化:key、稳定性与重组治理
android·前端
pengyu13 小时前
【Kotlin 协程修仙录 · 元婴境 · 中阶】 | 操作符真解:Flow 中间操作符与数据流变幻术
android·kotlin
pengyu14 小时前
【Kotlin 协程修仙录 · 元婴境 · 初阶】 | 冷流初啼:Flow 的基础与响应式编程的入门
android·kotlin