获取状态栏高度
一、方式一
Android31不支持
private static int getStatusBarHeight(Context context) {
// 获得状态栏高度
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
//注意:如果resourceId为0则会崩溃;
return context.getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
二、方式二
private int getStatusBarHeight() {
int statusBarHeight = 0;
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object object = c.newInstance();
Field field = c.getField("status_bar_height");
int x = (Integer) field.get(object);
statusBarHeight = getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
return statusBarHeight;
}
三、方式三
getWindow().getDecorView().setOnApplyWindowInsetsListener((v, insets) -> {
int statuBarHeight = insets.getStableInsetTop();
return insets;
});