實際項目中有時會碰到技術狀態欄高度的情況。有兩種方法可以做到:
第一種:
通過獲取到 status_bar_height的資源id,在計算其高度。
public int getStatusBarHeight(){
int height=0;
int resouceId=getResources().getIdentifier("status_bar_height", "dimen", "android");
if(resouceId>0){
height=getResources().getDimensionPixelSize(resouceId);
}
return height;
}
第二種方法,需要用到反射
/**
* 獲得狀態欄的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}