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
        }
    }
}
相关推荐
TechNomad7 小时前
Kotlin_Lambda编程详解
android·kotlin
熊猫_豆豆8 小时前
QT6 Android C++ 自制美观闹钟
android·c++·qt·闹钟
美狐美颜SDK开放平台8 小时前
Android/iOS直播APP平台开发中的视频美颜SDK优化技巧
android·ios·音视频·美颜sdk·第三方美颜sdk
聚美智数11 小时前
黄历查询-运势查询-国际法定节假日查询-API接口介绍
android·java·数据库
私人珍藏库12 小时前
[Android] 一木百宝箱-万能百宝箱+抖音去水印等几百种功能
android·人工智能·app·软件·多功能
wupa13 小时前
在 enableEdgeToEdge 模式下处理软键盘与自定义面板协同
android
plainGeekDev14 小时前
ProGuard → R8
android·java·kotlin
雨白15 小时前
C 语言字符串:从字符数组、指针到核心操作实战
android
Java小白笔记16 小时前
MySQL中存储过程大表分批删除历史数据
android·mysql·adb
aidou131416 小时前
Kotlin中沉浸式状态栏显示布局
android·kotlin·windowmanager·沉浸式状态栏·insetslistener·insetscompat·systembars