问题摘要
设置了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);//添加透明占位图
当然前提是你已做了浸入式处理,关于实现浸入式可以参考我的其他博客。