Android 实现顶部状态栏的沉浸模式(任意设置状态栏的颜色)
第一步、创建WindowsUtils工具类
public class WindowsUtils {
}
第二步、编写静态方法 setStatusBarColor
@RequiresApi(api = Build.VERSION_CODES.N)
public static void setStatusBarColor(Window window, Resources resources, int id){
//After LOLLIPOP not translucent status bar
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//Then call setStatusBarColor.
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(resources.getColor(id));
}
第三步、添加声明,并在Activity中测试
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置状态栏背景色
WindowsUtils.setStatusBarColor(getWindow(),getResources(),R.color.login_bg_color);
// 选择布局文件
setContentView(R.layout.activity_main);
}