改变沉浸式状态栏背景颜色

private void initWindow() {
    Window window=getWindow();
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
        //5.0以上的手机
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS|WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        ViewGroup content= (ViewGroup) findViewById(android.R.id.content);
        ViewGroup childView= (ViewGroup) content.getChildAt(0);
        if(childView!=null){
            childView.setFitsSystemWindows(true);
        }
        window.setStatusBarColor(Color.GREEN);
    }else if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
        //4.4以上5.0一下的手机
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        ViewGroup content= (ViewGroup) findViewById(android.R.id.content);
        ViewGroup childView= (ViewGroup) content.getChildAt(0);
        if(childView!=null){
            childView.setFitsSystemWindows(true);
        }

        View view=new View(this);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,getStatusHeight()));
        view.setBackgroundColor(Color.GREEN);
        content.addView(view);
    }
}

/**
 * 获取状态栏高度
 * @return
 */
private int getStatusHeight() {
    int statusHeight=-1;
    int resourceId=getResources().getIdentifier("status_bar_height","dimen","android");
    if(resourceId>0){
        return getResources().getDimensionPixelSize(resourceId);
    }
    return 0;
}

你可能感兴趣的:(改变沉浸式状态栏背景颜色)