美文网首页
折叠式Toolbar的沉浸式状态栏实现

折叠式Toolbar的沉浸式状态栏实现

作者: EnzoRay | 来源:发表于2019-10-10 10:58 被阅读0次

    首先使用这段代码让状态栏透明:

        /**
         * 使状态栏透明并且兼容有虚拟按键的手机
         */
        public static void setStatusBarTransparent(Activity activity) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                return;
            }
            // 实现功能
            final Window window = activity.getWindow();
            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);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            statusBarColor = window.getStatusBarColor();
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    

    然后绘制一个和状态栏一样高的View,并添加到decorView中:

        public static View createStatusView(Activity activity, int color) {
            if (activity == null) {
                return null;
            }
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                return null;
            }
            View statusView = new View(activity);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    TRStatusBarUtil.getStatusBarHeight(activity));
            statusView.setLayoutParams(params);
            // 设置背景色
            statusView.setBackgroundColor(color);
            // 添加 statusView 到布局中
            ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
            decorView.addView(statusView);
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                int systemUiVisibility = decorView.getSystemUiVisibility();
                activity.getWindow().getDecorView().
                        setSystemUiVisibility( systemUiVisibility | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }
            return statusView;
        }
    

    在Toolbar折叠的时候,需要通过AppBarLayout的OnOffsetChangedListener回调监听滑动的距离,从而设置statusBar的alpha值:

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            int abOffset = Math.abs(verticalOffset);
    
            float alpha = abOffset / (float) appBarLayout.getTotalScrollRange();//796
            if(statusBar != null){
                statusBar.setAlpha(alpha);
            }
        }
    

    这样当Toolbar上滑的时候状态栏alpha从0到1,下滑的时候从1到0,如此便实现了想要的效果,代码链接地址:
    https://github.com/leihupqrst/status_bar2

    相关文章

      网友评论

          本文标题:折叠式Toolbar的沉浸式状态栏实现

          本文链接:https://www.haomeiwen.com/subject/wzsopctx.html