Get screen width and height in Android

前端 未结 30 4084
野的像风
野的像风 2020-11-22 09:28

How can I get the screen width and height and use this value in:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, \"onM         


        
30条回答
  •  天涯浪人
    2020-11-22 10:10

    There is a very simple answer and without pass context

    public static int getScreenWidth() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }
    
    public static int getScreenHeight() {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }
    

    Note: if you want the height include navigation bar, use method below

    WindowManager windowManager =
            (WindowManager) BaseApplication.getApplication().getSystemService(Context.WINDOW_SERVICE);
        final Display display = windowManager.getDefaultDisplay();
        Point outPoint = new Point();
        if (Build.VERSION.SDK_INT >= 19) {
            // include navigation bar
            display.getRealSize(outPoint);
        } else {
            // exclude navigation bar
            display.getSize(outPoint);
        }
        if (outPoint.y > outPoint.x) {
            mRealSizeHeight = outPoint.y;
            mRealSizeWidth = outPoint.x;
        } else {
            mRealSizeHeight = outPoint.x;
            mRealSizeWidth = outPoint.y;
        }
    

提交回复
热议问题