沉浸式布局fitsSystemWindows="true"在fragment中失效的问题解决

问题摘要

设置了android:fitsSystemWindows="true"的fragemnt一开始有效,切换后便失效了。但是我们希望每个fragment浸入状态栏的背景不同,所以不能将原本设置在fragment中的fitsSystemWindows设置在activity_main.xml中。
在这里插入图片描述

解决思路

我们可以添加一个透明的状态栏占位视图,这样fragment的不同背景就会都能浸入状态栏。且不会切换后就无效。

实现代码

contentView为fragment视图的根布局

//添加透明占位图
    public static void addTransParentStatusView(Activity activity,ViewGroup contentView){
        View statusBarView = new View(activity);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                getStatusBarHeight(activity));
        //  statusBarView.setBackgroundColor(ContextCompat.getColor(activity, R.color.status));
        statusBarView.setBackgroundColor(activity.getResources().getColor(R.color.transParent));
        statusBarView.setLayoutParams(lp);
        contentView.addView(statusBarView, 0);
    }

其中R.color.transParent为color.xml中值为#00ffffff的透明颜色资源
状态栏高度获取(通过反射)

private static int getStatusBarHeight(Activity activity) {
        int result = 0;
        //获取状态栏高度的资源id
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

最后在要实现浸入的Fragment.java中添加以下代码:

addTransParentStatusView(getActivity(),contentView);//添加透明占位图

在这里插入图片描述
当然前提是你已做了浸入式处理,关于实现浸入式可以参考我的其他博客。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值