2014-10-31 66 views

回答

6

自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; 
} 

link to gist -> here