1.在style.xml的文件中修改主题:由于沉浸式状态栏是在API19之后出现的,所以我们只能在v19的value的文件夹下面来修改
<style name="AppBaseTheme" parent="@android:style/Theme.Holo.Light">
<!-- API 19 theme customizations can go here. -->
<!-- 沉浸式菜单 -->
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
这个步骤是设置状态栏为透明
2.在工具类中加上这两个方法
// 获取手机状态栏高度
public static 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;
}
// 获取ActionBar的高度
public static int getActionBarHeight(Context context) {
TypedValue tv = new TypedValue();
int actionBarHeight = 0;
if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize,
tv, true))// 如果资源是存在的、有效的
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
context.getResources().getDisplayMetrics());
}
return actionBarHeight;
}
3.正式开启
/**
* 开启沉浸式状态栏
*
* @param context
*/
public static void startImmersion(Context context) {
// 如果api>18则开启沉浸式菜单
if (android.os.Build.VERSION.SDK_INT > 18) {
Window window = ((Activity) context).getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// 设置根布局的内边距
View layout = ((Activity) context)
.findViewById(R.id.layout);
layout.setPadding(0, Utils.getActionBarHeight(context)
+ Utils.getStatusBarHeight(context), 0, 0);
// 创建TextView
TextView textView = new TextView(context);
LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, Utils.getStatusBarHeight(context));
textView.setBackgroundColor(context.getResources().getColor(R.color.actionBarColor));
textView.setLayoutParams(lParams);
// 获得根视图并把TextView加进去。
ViewGroup view = (ViewGroup)((Activity)context).getWindow().getDecorView();
view.addView(textView);
}
}