1、取得状态栏的高度值
通过反射获取状态栏高度(部分手机可能获取不到)
/**
* 获取状态栏的高度
* @return
*/
protected int getStatusBarHeight(){
try {
//通过反射获取到类
Class<?> aClass = Class.forName("com.android.internal.R$dimen");
//创建对象
Object o = aClass.newInstance();
//拿取属性
Field status_bar_height = aClass.getField("status_bar_height");
//获取值
Object o1 = status_bar_height.get(o);
int height = Integer.parseInt(o1.toString());
//
return getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return 0 ;
}
2、设置沉浸式状态栏(状态栏设置透明后,将顶层布局高度动态增加状态栏的高度)
/**
* 系统版本4.4或以上才可以设置沉浸式状态栏
*
* 设置沉浸式状态栏
*/
private void setStatus(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//设置状态栏透明
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//设置导航栏透明(如需要设置导航栏)
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
title_bar = (ViewGroup) findViewById(R.id.title_bar);
final int statusBarHeight = getStatusBarHeight();
title_bar.post(new Runnable() {
@Override
public void run() {
int height = title_bar.getHeight();
ViewGroup.LayoutParams layoutParams = title_bar.getLayoutParams();
layoutParams.height = statusBarHeight + height ;
title_bar.setLayoutParams(layoutParams);
}
});
}
}