How to change the status bar color in Android?

后端 未结 21 2257
旧时难觅i
旧时难觅i 2020-11-21 16:09

First of all it\'s not a duplicate as in How to change the background color of android status bar

How do I change the status bar color which should be same as in nav

21条回答
  •  醉梦人生
    2020-11-21 16:34

    If you want to work on Android 4.4 and above, try this. I refer to Harpreet's answer and this link. Android and the transparent status bar

    First, call setStatusBarColored method in Activity's onCreate method(I put it in a util class). I use a image here, you can change it to use a color.

    public static void setStatusBarColored(Activity context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window w = context.getWindow();
            w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = getStatusBarHeight(context);
    
            View view = new View(context);
            view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            view.getLayoutParams().height = statusBarHeight;
            ((ViewGroup) w.getDecorView()).addView(view);
            view.setBackground(context.getResources().getDrawable(R.drawable.navibg));
        }
    }
    
    public static int getStatusBarHeight(Activity context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
    

    Before:

    After:

    The color of the status bar has been changed, but the navi bar is cut off, so we need to set the margin or offset of the navi bar in the onCreate method.

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, (int)(this.getResources().getDimension(R.dimen.navibar_height)));
            layoutParams.setMargins(0, Utils.getStatusBarHeight(this), 0, 0);
    
            this.findViewById(R.id.linear_navi).setLayoutParams(layoutParams);
        }
    

    Then the status bar will look like this.

提交回复
热议问题