android实现透明状态栏,沉浸式状态栏

本文共有1642个字,关键词:

问题:安卓如何实现透明状态栏,沉浸式状态栏/变色状态栏?

方法:

在BaseActivity中调用下面两方法,并设置每个Activity需要显示的颜色

/**
 * 全透状态栏
 */
protected void setStatusBarFullTransparent() {
    if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
    } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //虚拟键盘也透明
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }
}
/**
 * 如果需要内容紧贴着StatusBar
 * 应该在对应的xml布局文件中,设置根布局fitsSystemWindows=true。
 */
private View contentViewGroup;

protected void setFitSystemWindow(boolean fitSystemWindow) {
    if (contentViewGroup == null) {
        contentViewGroup = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
    }
    contentViewGroup.setFitsSystemWindows(fitSystemWindow);
}

拓展:

推荐使用工具类StatusBarUtil

https://github.com/laobie/StatusBarUtil
或者
https://gitee.com/baijuncheng-open-source/statusbarutil?_from=gitee_search

参考:

https://www.jianshu.com/p/e89ee0a77bb5  关于如何实现Android透明状态栏的总结
版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。
添加新评论
暂无评论