Android中获取状态栏高度

发布于:2025-08-16 ⋅ 阅读:(19) ⋅ 点赞:(0)

获取状态栏高度工具类

获取到的高度是px像素值,如果想用dp需要转换

package com.utils;

import android.app.Activity;
import android.content.res.Resources;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class WindowManagerUtils {
    public static int getNavigationBarHeight(Activity activity) {
        int navigationBarHeight = 0;
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            navigationBarHeight = resources.getDimensionPixelSize(resourceId);
        }

        // 检查导航栏是否真的存在且可见
        boolean hasMenuKey = ViewConfiguration.get(activity).hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
        boolean isNavBarVisible = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION & activity.getWindow().getDecorView().getSystemUiVisibility()) == 0;

        if (!hasMenuKey && !hasBackKey && isNavBarVisible) {
            return navigationBarHeight;
        }
        return 0;
    }
    public static int getNavigationBarHeight(Window window) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+
            android.view.WindowInsets insets =                 
        window.getDecorView().getRootWindowInsets();
            if (insets != null) {
                return 
        insets.getInsets(android.view.WindowInsets.Type.navigationBars()).bottom;
            } else {
                return 0;
            }
        } else {
            // Android 5.0 - 10
            WindowInsetsCompat insetsCompat = 
        ViewCompat.getRootWindowInsets(window.getDecorView());
            if (insetsCompat != null) {
                return 
        insetsCompat.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom;
            } else {
                return 0;
            }
        }
    }
    public static int dp2px(int dp) {
        return Math.round(((float) dp) * getDensityDpiScale());
    }

    public static int px2dp(int px) {
        return Math.round(((float) px) / getDensityDpiScale());
    }
}

使用:

有的机型(测试发现OPPO一款机型)用getNavigationBarHeight(Activity activity)方法获取不到导航栏高度,可添加

getNavigationBarHeight(Window window)方法再次尝试获取高度,该方法需要在视图绘制完成后调用,例如在 onWindowFocusChanged() View.post(Runnable) 中使用

private fun openWindow() {
     val height = WindowManagerUtils.getNavigationBarHeight(requireActivity())
    lifecycleScope.launch {
        //通过测试发现部分机型获取不到导航栏高度
        height = WindowManagerUtils.getNavigationBarHeight(requireActivity().window)
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到