Android 相关区域高度获取

Android 手机屏幕

Android 相关区域高度获取_第1张图片
AndroidScreen.png

测试使用的手机信息:
手机型号: HUAWEI PLK-AL10
系统: Android 6.0
分辨率: 1920 x 1080

1、获取屏幕宽高(分辨率)

WindowManager wm = getWindowManager();

// 方式1
int w = 0,h = 0;
Point point = new Point(w,h);
wm.getDefaultDisplay().getSize(point);
int screenWidth1 = point.x;
int screenHeight1 = point.y;
// 输出结果:
// screenWidth1 = 1080
// screenHeight1 = 1812
System.out.println("screenWidth1 = " + screenWidth1);
System.out.println("screenHeight1 = " + screenHeight1);

// 方式2
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
int screenWidth2 = outMetrics.widthPixels;
int screenHeight2 = outMetrics.heightPixels;
// 输出结果:
// screenWidth2 = 1080
// screenHeight2 = 1812
System.out.println("screenWidth2 = " + screenWidth2);
System.out.println("screenHeight2 = " + screenHeight2);

2、获取状态栏高度

// 方式 1
int statusBarHeight1 = getResources().getDimensionPixelSize(getResources().getIdentifier("status_bar_height", "dimen", "android"));
// 输出结果:statusBarHeight 1 = 72
System.out.println("statusBarHeight1 = " + statusBarHeight1);

// 方式 2:重写 Activity 的 onWindowFocusChanged 方法
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    Rect frame = new Rect();
    getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
    int statusBarHeight2 = frame.top;
    // 输出结果:statusBarHeight 2 = 72
    System.out.println("statusBarHeight2 = " + statusBarHeight2);
}

3、获取标题栏高度

TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
    int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
    // 输出结果:actionBarHeight = 168
    System.out.println("actionBarHeight = " + actionBarHeight);
}

4、获取导航栏高度

Resources resources = getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
    int naviBarHeight = resources.getDimensionPixelSize(resourceId);
    // 输出结果:naviBarHeight = 108
    System.out.println("naviBarHeight = " + naviBarHeight);
}

总结

  1. 求某一区域高度也可以通过其它已知区域的高度运算而获取,例:
    Activity内容区域高度 = 获取的手机高度 - 标题栏高度 - 状态栏高度
  2. 上面获取手机分辨率的代码并不准确,因为从获取的屏幕宽高(分辨率)来看,其中高度并没有包含「导航栏」高度。
    实际的手机屏幕高度(1920)= 获取的手机高度(1812)+ 导航栏高度(108)

你可能感兴趣的:(Android 相关区域高度获取)