How to change the status bar color in Android?

后端 未结 21 2023
旧时难觅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:19

    this is very easy way to do this without any Library: if the OS version is not supported - under kitkat - so nothing happend. i do this steps:

    1. in my xml i added to the top this View:
    
    

    then i made this method:

     public void setStatusBarColor(View statusBar,int color){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
               Window w = getWindow();
               w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
               //status bar height
               int actionBarHeight = getActionBarHeight();
               int statusBarHeight = getStatusBarHeight();
               //action bar height
               statusBar.getLayoutParams().height = actionBarHeight + statusBarHeight;
               statusBar.setBackgroundColor(color);
         }
    }
    

    also you need those both methods to get action Bar & status bar height:

    public int getActionBarHeight() {
        int actionBarHeight = 0;
        TypedValue tv = new TypedValue();
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
        {
           actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
        }
        return actionBarHeight;
    }
    
    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
    

    then the only thing you need is this line to set status bar color:

    setStatusBarColor(findViewById(R.id.statusBarBackground),getResources().getColor(android.R.color.white));
    

提交回复
热议问题