/**
*方法1
* 获取状态栏高度
*通过反射的方式获取
* @param context * @return
*/
private static int getStateBar2(Context context) {
Class c = null;
try {
c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
int statusBarHeight = context.getResources().getDimensionPixelSize(x);
return statusBarHeight;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
*方法2
* 获取状态栏高度
*直接获取属性的方式
* @param context
* @return
*/
public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
在代码中的使用方式
private RelativeLayout rlTopBar; rlTopBar = (RelativeLayout) findViewById(R.id.rl_top_bar); //获取布局id RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) rlTopBar.getLayoutParams(); lp.topMargin = getStatusBarHeight(this); //将状态栏的高度赋给titlebar的上方 rlTopBar.setLayoutParams(lp); //将高度bar赋给title