安卓获取屏幕大小包括状态栏和软件导航栏的大小

9

如何获取包括导航栏和状态栏在内的屏幕像素大小?

我已经尝试使用DisplayMetrics获取大小,但大小不包括软件导航栏。

1个回答

13

自API 17(JELLY_BEAN_MR1)开始添加了软件导航,因此我们需要仅在API 17及以上版本中包括导航栏的大小。 请注意,在获取屏幕尺寸时,它是基于当前方向的

public void setScreenSize(Context context) {
    int x, y, orientation = context.getResources().getConfiguration().orientation;
    WindowManager wm = ((WindowManager) 
        context.getSystemService(Context.WINDOW_SERVICE));
    Display display = wm.getDefaultDisplay();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        Point screenSize = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            display.getRealSize(screenSize);
            x = screenSize.x;
            y = screenSize.y;
        } else {
            display.getSize(screenSize);
            x = screenSize.x;
            y = screenSize.y;
        }
    } else {
        x = display.getWidth();
        y = display.getHeight();
    }

    int width = getWidth(x, y, orientation);
    int height = getHeight(x, y, orientation);
}

private int getWidth(int x, int y, int orientation) {
    return orientation == Configuration.ORIENTATION_PORTRAIT ? x : y;
}

private int getHeight(int x, int y, int orientation) {
    return orientation == Configuration.ORIENTATION_PORTRAIT ? y : x;
}

链接到代码片段 -> 这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接