获取屏幕的宽高,可以直接使用的工具类
添加了不同版本的适配,可以获取到屏幕总高度、屏幕可用高度(排除状态栏与导航栏)等
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
}
}
}