Android获取屏幕高度、状态栏高度、标题栏高度
1、 屏幕区域的获取
1 DisplayMatrics matric = new DisplayMatrics();
2 Display display = activity.getWindowManager().getDefaultDisplay();
3 display.getMetrics(matric);
4 int width = matric.widthPixels; // 宽度
5 int height = matric.heightPixels; // 高度
2、应用区域的获取
1 Rect outRect = new Rect(); 2 activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
3 int width = outRect.width();
4 int height = outRect.height()
其中,outRect.top 即是状态栏高度。
3、view绘制区域获取
1 Rect outRect = new Rect(); 2 activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getDrawingRect(outRect);
3 int width = outRect.width();
4 int height = outRect.height();
用绘制区域的outRect.top - 应用区域的outRect.top 即是标题栏的高度。
注意: 如果刚启动Activity时就要计算这些数据,最好在 onWindowFocusChanged 函数中进行, 否则得到的某些数据可能是错误的,比如,应用区域高宽的获取。
1 public class ScreenSize extends Activity { 2 private TextView mScreenSizeView ; 3 @Override 4 public void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_screen_size); 7 mScreenSizeView = (TextView) findViewById(R.id.screen_size); 8 } 9 10 @Override 11 public void onWindowFocusChanged(boolean hasFocus) { 12 super.onWindowFocusChanged(hasFocus); 13 if(hasFocus){ 14 System.out.println("second"); 15 StringBuilder sb = new StringBuilder(); 16 Dimension dimen1 = getAreaOne(this); 17 Dimension dimen2 = getAreaTwo(this); 18 Dimension dimen3 = getAreaThree(this); 19 sb.append("Area one : \n\tWidth: "+dimen1.mWidth + ";\tHeight: "+dimen1.mHeight); 20 sb.append("\nArea two: \n\tWidth: "+dimen2.mWidth + ";\tHeight: "+dimen2.mHeight); 21 sb.append("\nArea three: \n\tWidth: "+dimen3.mWidth + ";\tHeight: "+dimen3.mHeight); 22 mScreenSizeView.setText(sb.toString()); 23 } 24 } 25 26 @Override 27 public boolean onCreateOptionsMenu(Menu menu) { 28 getMenuInflater().inflate(R.menu.activity_screen_size, menu); 29 return true; 30 } 31 32 private Dimension getAreaOne(Activity activity){ 33 Dimension dimen = new Dimension(); 34 Display disp = activity.getWindowManager().getDefaultDisplay(); 35 Point outP = new Point(); 36 disp.getSize(outP); 37 dimen.mWidth = outP.x ; 38 dimen.mHeight = outP.y; 39 return dimen; 40 } 41 private Dimension getAreaTwo(Activity activity){ 42 Dimension dimen = new Dimension(); 43 Rect outRect = new Rect(); 44 activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect); 45 System.out.println("top:"+outRect.top +" ; left: "+outRect.left) ; 46 dimen.mWidth = outRect.width() ; 47 dimen.mHeight = outRect.height(); 48 return dimen; 49 } 50 private Dimension getAreaThree(Activity activity){ 51 Dimension dimen = new Dimension(); 52 // 用户绘制区域 53 Rect outRect = new Rect(); 54 activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getDrawingRect(outRect); 55 dimen.mWidth = outRect.width() ; 56 dimen.mHeight = outRect.height(); 57 // end 58 return dimen;
59 }
1 private class Dimension { 2 public int mWidth ; 3 public int mHeight ; 4 public Dimension(){} 5 }