Android判断设备是否有NavigationBar(虚拟按键)并获取它的高度

转载请注明出处:
http://blog.csdn.net/aa464971/article/details/79347168

网上对于NavigationBar的判断有很多方法,但由于国内定制系统太多,导致兼容性不太好,这里提供一个实测兼容性比较好的。

/**
 * 判断是否有NavigationBar
 *
 * @param activity
 * @return
 */
public static boolean checkHasNavigationBar(Activity activity) {
    WindowManager windowManager = activity.getWindowManager();
    Display d = windowManager.getDefaultDisplay();

    DisplayMetrics realDisplayMetrics = new DisplayMetrics();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        d.getRealMetrics(realDisplayMetrics);
    }

    int realHeight = realDisplayMetrics.heightPixels;
    int realWidth = realDisplayMetrics.widthPixels;

    DisplayMetrics displayMetrics = new DisplayMetrics();
    d.getMetrics(displayMetrics);

    int displayHeight = displayMetrics.heightPixels;
    int displayWidth = displayMetrics.widthPixels;

    return (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;
}

/**
 * 获得NavigationBar的高度
 */
public static int getNavigationBarHeight(Activity activity) {
    int result = 0;
    Resources resources = activity.getResources();
    int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0 && checkHasNavigationBar(activity)) {
        result = resources.getDimensionPixelSize(resourceId);
    }
    return result;
}

你可能感兴趣的:(【Android,开源】)