工具类-StatusBarUtil

大家在工作中许多时候可能需要用到设置状态栏这里我们介绍一个状态来工具类StatusBarUtil当然这里是改造后的原版的还是在github上可以找找看就是那个star最多的。
下面是代码:

 public class StatusBarUtil {

    public static final int DEFAULT_STATUS_BAR_ALPHA = 112;
    private static final int FAKE_STATUS_BAR_VIEW_ID = R.id.statusbarutil_fake_status_bar_view;
    private static final int FAKE_TRANSLUCENT_VIEW_ID = R.id.statusbarutil_translucent_view;
    private static final int TAG_KEY_HAVE_SET_OFFSET = -123;

    /**
     * 设置状态栏颜色
     *
     * @param activity 需要设置的 activity
     * @param color    状态栏颜色值
     */
    public static void setColor(Activity activity, @ColorInt int color) {
        setColor(activity, color, DEFAULT_STATUS_BAR_ALPHA);
    }

    /**
     * 设置状态栏颜色
     *
     * @param activity       需要设置的activity
     * @param color          状态栏颜色值
     * @param statusBarAlpha 状态栏透明度
     */

    public static void setColor(Activity activity, @ColorInt int color, @IntRange(from = 0, to = 255) int statusBarAlpha) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            activity.getWindow().setStatusBarColor(calculateStatusColor(color, statusBarAlpha));
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
            View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID);
            if (fakeStatusBarView != null) {
                if (fakeStatusBarView.getVisibility() == View.GONE) {
                    fakeStatusBarView.setVisibility(View.VISIBLE);
                }
                fakeStatusBarView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha));
            } else {
                decorView.addView(createStatusBarView(activity, color, statusBarAlpha));
            }
            setRootView(activity);
        }
    }

    /**
     * 为滑动返回界面设置状态栏颜色
     *
     * @param activity 需要设置的activity
     * @param color    状态栏颜色值
     */
    public static void setColorForSwipeBack(Activity activity, int color) {
        setColorForSwipeBack(activity, color, DEFAULT_STATUS_BAR_ALPHA);
    }

    /**
     * 为滑动返回界面设置状态栏颜色
     *
     * @param activity       需要设置的activity
     * @param color          状态栏颜色值
     * @param statusBarAlpha 状态栏透明度
     */
    public static void setColorForSwipeBack(Activity activity, @ColorInt int color,
                                            @IntRange(from = 0, to = 255) int statusBarAlpha) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            ViewGroup contentView = ((ViewGroup) activity.findViewById(android.R.id.content));
            View rootView = contentView.getChildAt(0);
            int statusBarHeight = getStatusBarHeight();
            if (rootView != null && rootView instanceof CoordinatorLayout) {
                final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) rootView;
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    coordinatorLayout.setFitsSystemWindows(false);
                    contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha));
                    boolean isNeedRequestLayout = contentView.getPaddingTop() < statusBarHeight;
                    if (isNeedRequestLayout) {
                        contentView.setPadding(0, statusBarHeight, 0, 0);
                        coordinatorLayout.post(new Runnable() {
                            @Override
                            public void run() {
                                coordinatorLayout.requestLayout();
                            }
                        });
                    }
                } else {
                    coordinatorLayout.setStatusBarBackgroundColor(calculateStatusColor(color, statusBarAlpha));
                }
            } else {
                contentView.setPadding(0, statusBarHeight, 0, 0);
                contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha));
            }
            setTransparentForWindow(activity);
        }
    }

    /**
     * 设置状态栏纯色 不加半透明效果
     *
     * @param activity 需要设置的 activity
     * @param color    状态栏颜色值
     */
    public static void setColorNoTranslucent(Activity activity, @ColorInt int color) {
        setColor(activity, color, 0);
    }

    /**
     * 设置状态栏颜色(5.0以下无半透明效果,不建议使用)
     *
     * @param activity 需要设置的 activity
     * @param color    状态栏颜色值
     */
    @Deprecated
    public static void setColorDiff(Activity activity, @ColorInt int color) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return;
        }
        transparentStatusBar(activity);
        ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
        // 移除半透明矩形,以免叠加
        View fakeStatusBarView = contentView.findViewById(FAKE_STATUS_BAR_VIEW_ID);
        if (fakeStatusBarView != null) {
            if (fakeStatusBarView.getVisibility() == View.GONE) {
                fakeStatusBarView.setVisibility(View.VISIBLE);
            }
            fakeStatusBarView.setBackgroundColor(color);
        } else {
            contentView.addView(createStatusBarView(activity, color));
        }
        setRootView(activity);
    }

    /**
     * 使状态栏半透明
     * 

* 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity */ public static void setTranslucent(Activity activity) { setTranslucent(activity, DEFAULT_STATUS_BAR_ALPHA); } /** * 使状态栏半透明 *

* 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity * @param statusBarAlpha 状态栏透明度 */ public static void setTranslucent(Activity activity, @IntRange(from = 0, to = 255) int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } setTransparent(activity); addTranslucentView(activity, statusBarAlpha); } /** * 针对根布局是 CoordinatorLayout, 使状态栏半透明 *

* 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity * @param statusBarAlpha 状态栏透明度 */ public static void setTranslucentForCoordinatorLayout(Activity activity, @IntRange(from = 0, to = 255) int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } transparentStatusBar(activity); addTranslucentView(activity, statusBarAlpha); } /** * 设置状态栏全透明 * * @param activity 需要设置的activity */ public static void setTransparent(Activity activity) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } transparentStatusBar(activity); setRootView(activity); } /** * 使状态栏透明(5.0以上半透明效果,不建议使用) *

* 适用于图片作为背景的界面,此时需要图片填充到状态栏 * * @param activity 需要设置的activity */ @Deprecated public static void setTranslucentDiff(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 设置状态栏透明 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); setRootView(activity); } } /** * 为DrawerLayout 布局设置状态栏变色 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout * @param color 状态栏颜色值 */ public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { setColorForDrawerLayout(activity, drawerLayout, color, DEFAULT_STATUS_BAR_ALPHA); } /** * 为DrawerLayout 布局设置状态栏颜色,纯色 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout * @param color 状态栏颜色值 */ public static void setColorNoTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { setColorForDrawerLayout(activity, drawerLayout, color, 0); } /** * 为DrawerLayout 布局设置状态栏变色 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout * @param color 状态栏颜色值 * @param statusBarAlpha 状态栏透明度 */ public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color, @IntRange(from = 0, to = 255) int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } else { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } // 生成一个状态栏大小的矩形 // 添加 statusBarView 到布局中 ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); View fakeStatusBarView = contentLayout.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(color); } else { contentLayout.addView(createStatusBarView(activity, color), 0); } // 内容布局不是 LinearLayout 时,设置padding top if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { contentLayout.getChildAt(1) .setPadding(contentLayout.getPaddingLeft(), getStatusBarHeight() + contentLayout.getPaddingTop(), contentLayout.getPaddingRight(), contentLayout.getPaddingBottom()); } // 设置属性 setDrawerLayoutProperty(drawerLayout, contentLayout); addTranslucentView(activity, statusBarAlpha); } /** * 设置 DrawerLayout 属性 * * @param drawerLayout DrawerLayout * @param drawerLayoutContentLayout DrawerLayout 的内容布局 */ private static void setDrawerLayoutProperty(DrawerLayout drawerLayout, ViewGroup drawerLayoutContentLayout) { ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); drawerLayout.setFitsSystemWindows(false); drawerLayoutContentLayout.setFitsSystemWindows(false); drawerLayoutContentLayout.setClipToPadding(true); drawer.setFitsSystemWindows(false); } /** * 为DrawerLayout 布局设置状态栏变色(5.0以下无半透明效果,不建议使用) * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout * @param color 状态栏颜色值 */ @Deprecated public static void setColorForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // 生成一个状态栏大小的矩形 ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); View fakeStatusBarView = contentLayout.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(calculateStatusColor(color, DEFAULT_STATUS_BAR_ALPHA)); } else { // 添加 statusBarView 到布局中 contentLayout.addView(createStatusBarView(activity, color), 0); } // 内容布局不是 LinearLayout 时,设置padding top if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(), 0, 0); } // 设置属性 setDrawerLayoutProperty(drawerLayout, contentLayout); } } /** * 为 DrawerLayout 布局设置状态栏透明 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout */ public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) { setTranslucentForDrawerLayout(activity, drawerLayout, DEFAULT_STATUS_BAR_ALPHA); } /** * 为 DrawerLayout 布局设置状态栏透明 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout */ public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @IntRange(from = 0, to = 255) int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } setTransparentForDrawerLayout(activity, drawerLayout); addTranslucentView(activity, statusBarAlpha); } /** * 为 DrawerLayout 布局设置状态栏透明 * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout */ public static void setTransparentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } else { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); // 内容布局不是 LinearLayout 时,设置padding top if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(), 0, 0); } // 设置属性 setDrawerLayoutProperty(drawerLayout, contentLayout); } /** * 为 DrawerLayout 布局设置状态栏透明(5.0以上半透明效果,不建议使用) * * @param activity 需要设置的activity * @param drawerLayout DrawerLayout */ @Deprecated public static void setTranslucentForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 设置状态栏透明 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // 设置内容布局属性 ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); contentLayout.setFitsSystemWindows(true); contentLayout.setClipToPadding(true); // 设置抽屉布局属性 ViewGroup vg = (ViewGroup) drawerLayout.getChildAt(1); vg.setFitsSystemWindows(false); // 设置 DrawerLayout 属性 drawerLayout.setFitsSystemWindows(false); } } /** * 为头部是 ImageView 的界面设置状态栏全透明 * * @param activity 需要设置的activity * @param needOffsetView 需要向下偏移的 View */ public static void setTransparentForImageView(Activity activity, View needOffsetView) { setTranslucentForImageView(activity, 0, needOffsetView); } /** * 为头部是 ImageView 的界面设置状态栏透明(使用默认透明度) * * @param activity 需要设置的activity * @param needOffsetView 需要向下偏移的 View */ public static void setTranslucentForImageView(Activity activity, View needOffsetView) { setTranslucentForImageView(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); } /** * 为头部是 ImageView 的界面设置状态栏透明 * * @param activity 需要设置的activity * @param statusBarAlpha 状态栏透明度 * @param needOffsetView 需要向下偏移的 View */ public static void setTranslucentForImageView(Activity activity, @IntRange(from = 0, to = 255) int statusBarAlpha, View needOffsetView) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } setTransparentForWindow(activity); addTranslucentView(activity, statusBarAlpha); if (needOffsetView != null) { Object haveSetOffset = needOffsetView.getTag(TAG_KEY_HAVE_SET_OFFSET); if (haveSetOffset != null && (Boolean) haveSetOffset) { return; } ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) needOffsetView.getLayoutParams(); layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin + getStatusBarHeight(), layoutParams.rightMargin, layoutParams.bottomMargin); needOffsetView.setTag(TAG_KEY_HAVE_SET_OFFSET, true); } } /** * 为 fragment 头部是 ImageView 的设置状态栏透明 * * @param activity fragment 对应的 activity * @param needOffsetView 需要向下偏移的 View */ public static void setTranslucentForImageViewInFragment(Activity activity, View needOffsetView) { setTranslucentForImageViewInFragment(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); } /** * 为 fragment 头部是 ImageView 的设置状态栏透明 * * @param activity fragment 对应的 activity * @param needOffsetView 需要向下偏移的 View */ public static void setTransparentForImageViewInFragment(Activity activity, View needOffsetView) { setTranslucentForImageViewInFragment(activity, 0, needOffsetView); } /** * 为 fragment 头部是 ImageView 的设置状态栏透明 * * @param activity fragment 对应的 activity * @param statusBarAlpha 状态栏透明度 * @param needOffsetView 需要向下偏移的 View */ public static void setTranslucentForImageViewInFragment(Activity activity, @IntRange(from = 0, to = 255) int statusBarAlpha, View needOffsetView) { setTranslucentForImageView(activity, statusBarAlpha, needOffsetView); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { clearPreviousSetting(activity); } } /** * 隐藏伪状态栏 View * * @param activity 调用的 Activity */ public static void hideFakeStatusBarView(Activity activity) { ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { fakeStatusBarView.setVisibility(View.GONE); } View fakeTranslucentView = decorView.findViewById(FAKE_TRANSLUCENT_VIEW_ID); if (fakeTranslucentView != null) { fakeTranslucentView.setVisibility(View.GONE); } } public static void setLightMode(Activity activity, View statusBarView, int backgroundColor, boolean ifNeedChangeColor) {// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); statusBarView.setBackgroundColor(activity.getResources().getColor(backgroundColor)); return; } else if (setMIUIStatusBarDarkIcon(activity, true)) { statusBarView.setBackgroundColor(activity.getResources().getColor(backgroundColor)); return; } else if (setMeizuStatusBarDarkIcon(activity, true)) { statusBarView.setBackgroundColor(activity.getResources().getColor(backgroundColor)); return; } } if (ifNeedChangeColor) { statusBarView.setVisibility(View.VISIBLE); statusBarView.setBackgroundColor(activity.getResources().getColor(R.color.BlackColor)); } } public static void setDarkMode(Activity activity, View statusBarView, int backgroundColor, boolean ifNeedChangeColor) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); statusBarView.setBackgroundColor(activity.getResources().getColor(backgroundColor)); return; } else if (setMIUIStatusBarDarkIcon(activity, false)) { statusBarView.setBackgroundColor(activity.getResources().getColor(backgroundColor)); return; } else if (setMeizuStatusBarDarkIcon(activity, false)) { statusBarView.setBackgroundColor(activity.getResources().getColor(backgroundColor)); return; } } if (ifNeedChangeColor) { statusBarView.setVisibility(View.VISIBLE); statusBarView.setBackgroundColor(activity.getResources().getColor(R.color.BlackColor)); } } /** * 修改 MIUI V6 以上状态栏颜色 */ private static boolean setMIUIStatusBarDarkIcon(@NonNull Activity activity, boolean darkIcon) { Class clazz = activity.getWindow().getClass(); try { Window window = activity.getWindow(); int darkModeFlag = 0; Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams"); Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE"); darkModeFlag = field.getInt(layoutParams); Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class); extraFlagField.invoke(activity.getWindow(), darkIcon ? darkModeFlag : 0, darkModeFlag); if (darkIcon) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); } else { int flag = window.getDecorView().getSystemUiVisibility() & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; window.getDecorView().setSystemUiVisibility(flag); } return true; } catch (Exception e) { return false; } } /** * 修改魅族状态栏字体颜色 Flyme 4.0 */ private static boolean setMeizuStatusBarDarkIcon(@NonNull Activity activity, boolean darkIcon) { try { WindowManager.LayoutParams lp = activity.getWindow().getAttributes(); Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON"); Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags"); darkFlag.setAccessible(true); meizuFlags.setAccessible(true); int bit = darkFlag.getInt(null); int value = meizuFlags.getInt(lp); if (darkIcon) { value |= bit; } else { value &= ~bit; } meizuFlags.setInt(lp, value); activity.getWindow().setAttributes(lp); return true; } catch (Exception e) { return false; } } /////////////////////////////////////////////////////////////////////////////////// @TargetApi(Build.VERSION_CODES.KITKAT) private static void clearPreviousSetting(Activity activity) { ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { decorView.removeView(fakeStatusBarView); ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); rootView.setPadding(0, 0, 0, 0); } } /** * 添加半透明矩形条 * * @param activity 需要设置的 activity * @param statusBarAlpha 透明值 */ private static void addTranslucentView(Activity activity, @IntRange(from = 0, to = 255) int statusBarAlpha) { ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); View fakeTranslucentView = contentView.findViewById(FAKE_TRANSLUCENT_VIEW_ID); if (fakeTranslucentView != null) { if (fakeTranslucentView.getVisibility() == View.GONE) { fakeTranslucentView.setVisibility(View.VISIBLE); } fakeTranslucentView.setBackgroundColor(Color.argb(statusBarAlpha, 0, 0, 0)); } else { contentView.addView(createTranslucentStatusBarView(activity, statusBarAlpha)); } } /** * 生成一个和状态栏大小相同的彩色矩形条 * * @param activity 需要设置的 activity * @param color 状态栏颜色值 * @return 状态栏矩形条 */ private static View createStatusBarView(Activity activity, @ColorInt int color) { return createStatusBarView(activity, color, 0); } /** * 生成一个和状态栏大小相同的半透明矩形条 * * @param activity 需要设置的activity * @param color 状态栏颜色值 * @param alpha 透明值 * @return 状态栏矩形条 */ private static View createStatusBarView(Activity activity, @ColorInt int color, int alpha) { // 绘制一个和状态栏一样高的矩形 View statusBarView = new View(activity); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight()); statusBarView.setLayoutParams(params); statusBarView.setBackgroundColor(calculateStatusColor(color, alpha)); statusBarView.setId(FAKE_STATUS_BAR_VIEW_ID); return statusBarView; } /** * 设置根布局参数 */ private static void setRootView(Activity activity) { ViewGroup parent = (ViewGroup) activity.findViewById(android.R.id.content); for (int i = 0, count = parent.getChildCount(); i < count; i++) { View childView = parent.getChildAt(i); if (childView instanceof ViewGroup) { childView.setFitsSystemWindows(true); ((ViewGroup) childView).setClipToPadding(true); } } } /** * 设置透明 */ private static void setTransparentForWindow(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().setStatusBarColor(Color.TRANSPARENT); activity.getWindow() .getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow() .setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } /** * 使状态栏透明 */ @TargetApi(Build.VERSION_CODES.KITKAT) private static void transparentStatusBar(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } else { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } /** * 创建半透明矩形 View * * @param alpha 透明值 * @return 半透明 View */ private static View createTranslucentStatusBarView(Activity activity, int alpha) { // 绘制一个和状态栏一样高的矩形 View statusBarView = new View(activity); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight()); statusBarView.setLayoutParams(params); statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0)); statusBarView.setId(FAKE_TRANSLUCENT_VIEW_ID); return statusBarView; } /** * 获取状态栏高度 * * @return 状态栏高度 */ public static int getStatusBarHeight() { // 获得状态栏高度 int resourceId = ShowSelfApp.getContext().getResources().getIdentifier("status_bar_height", "dimen", "android"); return ShowSelfApp.getContext().getResources().getDimensionPixelSize(resourceId); } /** * 计算状态栏颜色 * * @param color color值 * @param alpha alpha值 * @return 最终的状态栏颜色 */ private static int calculateStatusColor(@ColorInt int color, int alpha) { if (alpha == 0) { return color; } float a = 1 - alpha / 255f; int red = color >> 16 & 0xff; int green = color >> 8 & 0xff; int blue = color & 0xff; red = (int) (red * a + 0.5); green = (int) (green * a + 0.5); blue = (int) (blue * a + 0.5); return 0xff << 24 | red << 16 | green << 8 | blue; } public static void setActivityTranslucent(Activity activity) { // 5.0 以上 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 这个怎么写有没有思路?看源码 29次 View decorView = activity.getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } // 4.4 - 5.0 之间 采用一个技巧,首先把他弄成全屏,在状态栏的部分加一个布局 else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } public static void setStatusBarColor(Activity activity, int color) { // 5.0 以上 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 直接调用系统提供的方法 setStatusBarColor activity.getWindow().setStatusBarColor(color); } // 4.4 - 5.0 之间 采用一个技巧,首先把他弄成全屏,在状态栏的部分加一个布局 else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 首先把他弄成全屏(),在状态栏的部分加一个布局 // activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // 电量 时间 网络状态 都还在 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // 在状态栏的部分加一个布局 setContentView 源码分析,自己加一个布局 (高度是状态栏的高度) View view = new View(activity); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight()); view.setLayoutParams(params); view.setBackgroundColor(color); // android:fitsSystemWindows="true" 每个布局都要写 ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); decorView.addView(view); // 获取activity中setContentView布局的根布局 ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); contentView.setPadding(0, getStatusBarHeight(), 0, 0); // View activityView = contentView.getChildAt(0); // activityView.setFitsSystemWindows(true); // activityView.setPadding(0,getStatusBarHeight(activity),0,0); } } /** * 清除状态栏内容 * * @param activity 当前activity */ public static void removeStatusBar(Activity activity) { Window window = activity.getWindow(); if (android.os.Build.VERSION.SDK_INT >= 19) { window.getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE //让系统主内容占据状态栏空间 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } /** * 获取屏幕高度 * * @return 屏幕绝对高度 */ @SuppressWarnings({"ConstantConditions", "unchecked"}) private static int getScreenDPI(Context context) { int dpi = 0; WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics displayMetrics = new DisplayMetrics(); Class c; try { c = Class.forName("android.view.Display"); Method method = c.getMethod("getRealMetrics", DisplayMetrics.class); method.invoke(display, displayMetrics); dpi = displayMetrics.heightPixels; } catch (Exception e) { e.printStackTrace(); } return dpi; } /** * 获取底部虚拟键盘的高度 * * @param context 上下文 * @return 屏幕高度 */ @SuppressWarnings("ConstantConditions") private static int getScreenHeight(Context context) { WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics out = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(out); return out.heightPixels; } /** * 获取虚拟键盘的高度 * * @return 虚拟键盘高度 */ public static int getBottomStatusHeight(Context context) { int totlaHeight = getScreenDPI(context); int contentHeight = getScreenHeight(context); return totlaHeight - contentHeight; } }

这里需要注意的几点
1.需要添加一个ids.xml在里面添加如下内容

 
 

2.setMIUIStatusBarDarkIcon这个方法添加了对于miui9.0以上的支持(以前的处理对弈miui9及以上改变mode是无效的)
3.使用
3.1在activity中设置

  StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);

3.2如果要设置全屏并清除状态栏设置

  StatusBarUtil.removeStatusBar(this);//设置全屏

3.3设置drak和light mode

View statusBar = findViewById(布局里面代替状态栏背景的id);
statusBar.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,StatusBarUtil.getStatusBarHeight()));
StatusBarUtil.setDarkMode(getActivity(), statusBar, 颜色id, false);

基本的使用就用到了这些希望能帮助大家解决问题。

你可能感兴趣的:(工具类)