---
title: "Android获取状态栏高度"
author: "lovelease"
date: "2015-01-28T12:04:38Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2015-01-28T12:04:38Z"
id: 2180751
url: "https://lovelease.iteye.com/blog/2180751"
---

获取状态栏高度有两种方法：
1.如果是在Activity中：

```java

    Rect localRect = new Rect();  
    getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);  
    statusHeight = localRect.top;

```

限制：由于getWindow()方法在Activity中，所以只能在Activity中使用 ，当然了，如果你传递的context对象可以被强转成Activity，那也可以，如下：

```java

((Activity)mContext).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect); 

```

如果不能强转，而又不在activity中，还可以利用反射机制获取，这种方法只要有context对象就可以使用：

```java

private int getStatusBarHeight(Context context) {
		Class<?> c = null;  
        Object obj = null;  
        Field field = null;  
        int x = 0, statusBarHeight = 0;  
        try {  
            c = Class.forName("com.android.internal.R$dimen");  
            obj = c.newInstance();  
            field = c.getField("status_bar_height");  
            x = Integer.parseInt(field.get(obj).toString());  
            statusBarHeight = context.getResources().getDimensionPixelSize(x);  
        } catch (Exception e1) {  
            e1.printStackTrace();  
        }  
        return statusBarHeight;
	}

```