沉浸式状态栏兼容4.4版本 4.4以下暂时无法实现
1、原来刚刚开始开发的时候,我搞这个沉浸式状态栏搞了很久,一直网上找资料,花了很长的时间才搞定,而且还一大堆问题,不多说 下面上代码
package com.example.chao.myview.view.viewI1;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import static android.view.View.SYSTEM_UI_FLAG_FULLSCREEN;
import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
import static android.view.View.SYSTEM_UI_FLAG_LOW_PROFILE;
/**
* Created by yang2 on 2017/9/19.
*/
public class StatusbarUtil {
/**
* 设置颜色
* @param activity
* @param color
*/
public static void setStatusBarColor(Activity activity,int color){
//5.0
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.LOLLIPOP){
activity.getWindow().setStatusBarColor(color);
}else if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.KITKAT){
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
View view = new View(activity);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,getStatusBarHeight(activity)));
view.setBackgroundColor(color);
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
decorView.addView(view);
ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
contentView.setPadding(0,getStatusBarHeight(activity),0,0);
}
}
/**
* 获取状态栏高度
* @param activity
* @return 状态栏高度
*/
public static int getStatusBarHeight(Activity activity) {
Resources resources = activity.getResources();
//status_bar_height 这是状态栏资源名就能拿到高度
return resources.getDimensionPixelOffset(resources.getIdentifier("status_bar_height", "dimen", "android"));
}
/**
* 设置Activity全屏
* @param activity
*/
public static void setActivityTranslucent(Activity activity){
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.LOLLIPOP){
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
decorView.setSystemUiVisibility(SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
}else if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.KITKAT){
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
}