SystemBarUtil 工具类

SystemBarUtil 工具类

工具类,提供了系统栏高度和屏幕宽高获取方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

import android.app.Activity
import android.content.Context
import android.graphics.Point
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager

/**
* 工具类,提供了系统栏高度和屏幕宽高获取方法
*/
object SystemBarUtil {

/**
* 获取状态栏高度
*/
@JvmStatic
fun getStatusBarHeight(context: Context): Int {
var height = 0
try {
val resourceId = context.applicationContext.resources.getIdentifier(
"status_bar_height",
"dimen",
"android"
)
if (resourceId > 0) {
height =
context.applicationContext.resources.getDimensionPixelSize(resourceId)
}
} catch (e: Exception) {
}
return height
}

/**
* 获取系统导航栏高度
*/
@JvmStatic
fun getNavigationBarHeight(context: Context): Int {
var height = 0
try {
val resourceId = context.applicationContext.resources.getIdentifier(
"navigation_bar_height",
"dimen",
"android"
)
if (resourceId > 0) {
height =
context.applicationContext.resources.getDimensionPixelSize(resourceId)
}
} catch (e: Exception) {
}
return height
}

private const val NAVIGATION = "navigationBarBackground"

// 该方法需要在View完全被绘制出来之后调用
@JvmStatic
private fun isNavigationBarVisible(activity: Activity): Boolean {
val vp = activity.window.decorView as ViewGroup?
if (vp != null) {
for (i in 0 until vp.childCount) {
vp.getChildAt(i).context.packageName
if (vp.getChildAt(i).id !== View.NO_ID &&
NAVIGATION == activity.resources.getResourceEntryName(vp.getChildAt(i).id)
) {
return true
}
}
}
return false
}

/**
* 获取屏幕的物理大小 px
*/
@JvmStatic
fun getDeviceScreenSize(context: Context): Point {
val appContext = context.applicationContext
val wm = appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val point = Point(0, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
wm.defaultDisplay.getRealSize(point)
} else {
wm.defaultDisplay.getSize(point)
}
return point
}

/**
* 获取显示屏幕的宽高 px
*/
@JvmStatic
fun getDisplaySize(context: Context): Point {
val point = Point(0, 0)
val dm = context.applicationContext.resources.displayMetrics
point.x = dm.widthPixels
point.y = dm.heightPixels
return point
}
}
作者

Dench

发布于

2023-02-15

更新于

2023-02-15

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×