调用setStatusBarColor ANDROID

use*_*517 2 java android statusbar buttonclick

如何在按钮上调用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"));
                }
            }
Run Code Online (Sandbox Code Playgroud)

这是我的按钮监听器

public void addButtonListener() {

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

            public void onClick(View view) {
                setStatusBarColor();
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

And*_*n K 7

将方法调用更改为此

在活动中

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

在片段中:

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

或者从方法中删除参数

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);
    }
}
Run Code Online (Sandbox Code Playgroud)