android实现沉浸栏效果主要有两种方案
1.设置状态栏的背景色跟标题栏的背景色一样
2.将布局顶到状态栏上面(适用于图片背景)
看效果:
第一种实现方案,附上代码
package com.ikuaibaike.qishou.kuaibaike.utils;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
public class StatusBarCompat {
private static final int INVALID_VAL = -1;
private static final int COLOR_DEFAULT = Color.parseColor("#20000000");
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void compat(Activity activity, int statusColor)
{
//当前手机版本为5.0及以上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
if (statusColor != INVALID_VAL)
{
activity.getWindow().setStatusBarColor(statusColor);
}
return;
}
//当前手机版本为4.4
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
{
int color = COLOR_DEFAULT;
ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
if (statusColor != INVALID_VAL)
{
color = statusColor;
}
View statusBarView = new View(activity);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
getStatusBarHeight(activity));
statusBarView.setBackgroundColor(color);
contentView.addView(statusBarView, lp);
}
}
public static void compat(Activity activity)
{
compat(activity, INVALID_VAL);
}
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;
}
}
对于很多页面都是一样的,就在baseActivity加上一行代码就行
第二种实现方式:可以在代码中实现,也可以在java代码中实现
xml:在根布局加上android:fitsSystemWindows="true"
java代码:oncreate()中写
/**
* 隐藏状态栏
* @param context
*/
public static void hideStatusLan(Activity context){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}