Search code examples
javaandroidstatusbarbuttonclick

Calling setStatusBarColor ANDROID


How can I call setStatusBarColor on a buttonclick? I have the event listener code but I'm unsure how to call this method. I'm trying to change the status bar color on button click.

Here's my code:

public static void setStatusBarColor(Activity activity, int statusBarColor) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    // If both system bars are black, we can remove these from our layout,
                    // removing or shrinking the SurfaceFlinger overlay required for our views.
                    Window window = activity.getWindow();
                    if (statusBarColor == Color.BLACK && window.getNavigationBarColor() == Color.BLACK) {
                        window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                    } else {
                        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                    }
                    window.setStatusBarColor(Color.parseColor("#4CAF50"));
                }
            }

Here is my button listener

public void addButtonListener() {

        Button = (Button) findViewById(R.id.Button);
        Button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                setStatusBarColor();
            }
        });
    }

Solution

  • Change your method call to this

    In Activity

    public void onClick(View view) {
        setStatusBarColor(this, Color.parseColor("#4CAF50"));
    }
    

    In Fragment:

    public void onClick(View view) {
        setStatusBarColor(getActivity() , Color.parseColor("#4CAF50"));  
    }  
    

    Or remove the parameter from method

    public void onClick(View view) {
        setStatusBarColor();  
    } 
    
    public static void setStatusBarColor() {
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // If both system bars are black, we can remove these from our layout,
            // removing or shrinking the SurfaceFlinger overlay required for our views.
    
    
            //change here
             Window window = activity.getWindow();
    
            // By -->>>>> Window window = getWindow();
    
            //or by this if call in Fragment
            // -->>>>> Window window = getActivity().getWindow();
    
    
            int statusBarColor = Color.parseColor("#4CAF50");
    
            if (statusBarColor == Color.BLACK && window.getNavigationBarColor() == Color.BLACK) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            } else {
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            }
            window.setStatusBarColor(statusBarColor);
        }
    }