Android获取状态栏高度

获取状态栏高度有两种方法:
1.如果是在Activity中:
    Rect localRect = new Rect();  
    getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);  
    statusHeight = localRect.top;

限制:由于getWindow()方法在Activity中,所以只能在Activity中使用 ,当然了,如果你传递的context对象可以被强转成Activity,那也可以,如下:
((Activity)mContext).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect); 

如果不能强转,而又不在activity中,还可以利用反射机制获取,这种方法只要有context对象就可以使用:
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;
	}

猜你喜欢

转载自lovelease.iteye.com/blog/2180751