调用 setStatusBarColor ANDROID

Calling setStatusBarColor ANDROID

如何在单击按钮时调用 setStatusBarColor?我有事件侦听器代码,但不确定如何调用此方法。我正在尝试更改按钮单击时的状态栏颜色。

这是我的代码:

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"));
                }
            }

这是我的按钮监听器

public void addButtonListener() {

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

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

将您的方法调用更改为此

在Activity

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

在片段中:

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

或从方法中删除参数

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);
    }
}