Android 如何正確的獲取屏幕高度

一、問題描述


目前很多手機主流手機將Back鍵、Home鍵、Menu鍵設計成虛擬功能鍵。當我們獲取屏幕高度時就會遇到問題,獲取到的並不是實際的高度,從而不能正確的佈局。


下邊通過倆種方式獲取:
1.通過判斷(Build.VERSION.SDK_INT >= 17)使用方法getRealMetrics()獲取。
2.通過反射調用getRealMetrics獲取。


二、正確方法

// 方法一
public void initScreenInfo(Context context) {
    try {
        DisplayMetrics dm = new DisplayMetrics();

        // 測試設備 1440*2960 --- SDK VERSION 24 --- 包含虛擬功能鍵
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealMetrics(dm); // 包含虛擬功能鍵高度 dm.heightPixels = 2960
        } else {
            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm); // 不包含虛擬功能鍵高度 dm.heightPixels = 2768
        }

        int WIDTH = Math.min(dm.widthPixels, dm.heightPixels);
        int HEIGHT = Math.max(dm.widthPixels, dm.heightPixels);
        float DENSITY = dm.density;
        int DENSITY_DPI = dm.densityDpi;
        float SCALED_DENSITY = dm.scaledDensity;

        tv.setText("   WIDTH:" + WIDTH + "   HEIGHT:" + HEIGHT + "   DENSITY:" + DENSITY + "   DENSITY_DPI:" + DENSITY_DPI + "   SCALED_DENSITY:" + SCALED_DENSITY);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

// 方法二
private void initScreenInfo() {
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics dm = new DisplayMetrics();
    Class c;
    try {
        c = Class.forName("android.view.Display");
        Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
        method.invoke(display, dm);
        int HEIGHT = dm.heightPixels;
        int WIDTH = dm.widthPixels;
        tv2.setText("   WIDTH:" + WIDTH + "   HEIGHT:" + HEIGHT);
    } catch (Exception e) {
        e.printStackTrace();
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章