android 中获取 状态栏,标题栏,ActionBar的高度

一、屏幕高度和宽度获取方法

  1. int screenWidth,screenHeight;    
  2. WindowManager windowManager = getWindowManager();    
  3. Display display = windowManager.getDefaultDisplay();    
  4. screenWidth = display.getWidth();    
  5. screenHeight = display.getHeight();  

另外一种
  1. DisplayMetrics dm = new DisplayMetrics();       
  2. getWindowManager().getDefaultDisplay().getMetrics(dm);       
  3. int screenWidth = dm.widthPixels;       
  4. int screenHeight = dm.heightPixels;   


二、状态栏高度获取方法

  1. Rect frame = new Rect();  
  2. getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
  3. int statusBarHeight = frame.top;  

上面这种方法基本上是可以的,但是下面这种方法更牛逼

  1. private int getStatusBarHeight() {  
  2.         Class<?> c = null;  
  3.         Object obj = null;  
  4.         Field field = null;  
  5.         int x = 0;  
  6.         try {  
  7.             c = Class.forName("com.android.internal.R$dimen");  
  8.             obj = c.newInstance();  
  9.             field = c.getField("status_bar_height");  
  10.             x = Integer.parseInt(field.get(obj).toString());  
  11.             return getResources().getDimensionPixelSize(x);  
  12.         } catch (Exception e1) {  
  13.             Log.d(TAG, "get status bar height fail");  
  14.             e1.printStackTrace();  
  15.             return 75;  
  16.         }  
  17.     }  

三、获取标题栏的高度

  1. int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
  2. //statusBarHeight是上面状态栏的高度  
  3. int titleBarHeight = contentTop - statusBarHeight;  

四、获取ActionBar高度

  1. int actionBarHeight = getActionBar().getHeight();  

注意 :如果是在Activity的onCreate函数中就开始使用,需要将其放入Runnable中调用,因为这个时候控件的高度可能还没有确定。

  1. View root;  
  2. 。。。。  
  3. root.post(new Runnable() {  
  4.             @Override  
  5.             public void run() {  
  6.                 //To change body of implemented methods use File | Settings | File Templates.  
  7.                 getActivityContentHeight();  
  8.             }  
  9.         }); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值